获取 CKEditor 中所选内容的样式值

Get style value of selection in CKEditor

本文关键字:样式 CKEditor 获取      更新时间:2023-09-26

我正在使用CKEditor的编辑功能,但使用我自己的UI控件,调用CKEditor的api来执行其命令。 例如,

var style = new CKEDITOR.style({
    element: 'span',
    attributes: {
        'style': 'font-size: 20px'
    }
});
editor.applyStyle(style);

以设置所选文本的字体大小。

问题是我需要一种方法来了解当前所选文本的状态,以便我可以相应地更新控件。大胆吗?然后,粗体按钮应处于激活状态,单击它应删除粗体,而不是尝试再次添加它。

有没有办法查询CKEditor以获取当前所选文本的某些样式属性?很像tinymce.activeEditor.queryCommandValue('bold')在tinyMCE中的工作方式。

通常,创建按钮命令样式三重奏的最佳方法是在 basicstyles 插件中完成:

var style = new CKEDITOR.style( { ... } );
editor.attachStyleStateChange( style, function( state ) {
    !editor.readOnly && editor.getCommand( 'commandName' ).setState( state );
} );
editor.addCommand( 'commandName', new CKEDITOR.styleCommand( style ) );
editor.ui.addButton( 'buttonName', {
    label: 'buttonLabel',
    command: 'commandName'
} );

此代码将处理所有事情 - 命令和按钮状态将根据选择更改进行更新。您还可以轻松获取命令状态:

editor.getCommand( 'commandName' ).state; // Returns on of CKEDITOR.TRISTATE_*.

但是,如果要直接查询样式的状态,则可以使用 style.checkActive() 方法:

style.checkActive( editor.elementPath(), editor );

您无需创建命令和按钮即可使其正常工作。

编辑

CKEditor 样式系统有其局限性。例如,样式中不能有可变的字体大小。这意味着要检查当前字体大小,您需要在 DOM 中进行快速搜索:

function getFontSize() {
    var span = editor.elementPath().contains( isFontSizeSpan );
    return span ? span.getStyle( 'font-size' ) : null;
    function isFontSizeSpan( el ) {
        return el.is( 'span' ) && el.getStyle( 'font-size' );
    }
}

现在,只需在 editor#selectionChange 事件侦听器中使用此方法即可更新控件的值。