在CKEditor中获取选择的样式值

Gor*_*per 5 javascript ckeditor

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

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

editor.applyStyle(style);
Run Code Online (Sandbox Code Playgroud)

设置所选文本的字体大小.

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

有没有办法查询CKEditor当前所选文本的某些样式属性?就像tinymce.activeEditor.queryCommandValue('bold')在tinyMCE中如何工作一样.

Rei*_*mar 1

通常,创建按钮命令风格三重奏的最佳方法就像在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'
} );
Run Code Online (Sandbox Code Playgroud)

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

editor.getCommand( 'commandName' ).state; // Returns on of CKEDITOR.TRISTATE_*.
Run Code Online (Sandbox Code Playgroud)

但是,如果你想直接查询样式的状态,那么你可以使用以下style.checkActive()方法:

style.checkActive( editor.elementPath(), editor );
Run Code Online (Sandbox Code Playgroud)

您不需要创建命令和按钮即可使其工作。

编辑

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' );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 样式实例代表具体样式。因此,每种字体大小都有一个样式实例,您需要检查每个样式实例以找到应用的样式实例。 (2认同)
  • 如果你想给用户充分的自由,那么你可以使用 `CKEDITOR.style` 来应用或删除跨度,但你需要在 DOM 中查找当前的字体大小。要做到这一点,只需使用 [`contains()`](http://docs.ckeditor.com/#!/api/CKEDITOR.dom.elementPath-) 通过 `editor.elementPath()` 搜索正确的跨度method-contains) 方法(它接受回调)并检查它适用的大小。 (2认同)