自定义 CKEditor Format 插件到一个简单的按钮

dzo*_*jan 2 ckeditor

内置格式插件是可能标签的下拉列表(h1、h2、p、pre..)。标签列表可以在配置文件中轻松配置。

我只使用一个标签,因此下拉菜单只会使工具栏复杂化并影响可用性。

是否可以自定义现有插件或创建新插件:

1) 是简单的按钮而不是下拉菜单,带有自定义图标

2) 单击按钮时,会将预定义的格式 H1 添加到所选文本

简单地说,将模拟下拉项目选择的工具栏按钮单击“标题 1”。

Mar*_*ski 5

据我回忆格式没有为外部调用提供方便的接口,但您可以创建自己的插件。

本质上归结为使用CKEDITOR.style对象:

// Creates a style object, 
var styleObj = new CKEDITOR.style( { element: 'pre' } );

editor.applyStyle( styleObj );
// Or if you wish to remove style:
// editor.removeStyle( styleObj );
Run Code Online (Sandbox Code Playgroud)

我创建了简单的、功能齐全的示例插件,称为myFormat

( function() {

    "use strict";

    var pluginName = 'myFormat';

    CKEDITOR.plugins.add( pluginName, {
        icons: pluginName, // If you wish to have an icon...

        init: function( editor ) {
            // Tagname which you'd like to apply.
            var tag = 'h2',
                // Note: that we're reusing.
                //style = new CKEDITOR.style( editor.config[ 'format_' + tag ] );
                style = new CKEDITOR.style( { element: 'pre' } );

            // Creates a command for our plugin, here command will apply style. All the logic is
            // inside CKEDITOR.styleCommand#exec function so we don't need to implement anything.
            editor.addCommand( pluginName, new CKEDITOR.styleCommand( style ) );

            // This part will provide toolbar button highlighting in editor.
            editor.attachStyleStateChange( style, function( state ) {
                !editor.readOnly && editor.getCommand( pluginName ).setState( state );
            } );

            // This will add button to the toolbar.
            editor.ui.addButton( 'MyFormat', {
                label: 'Click to apply format',
                command: pluginName,
                toolbar: 'insert,5'
            } );
        }
    } );

} )();
Run Code Online (Sandbox Code Playgroud)

只需将代码放在<ckeditorDirectory>/ckeditor-dev/plugins/myFormat/plugin.js.

不要忘记修改您的 CKEditor 配置以包含myFormat插件,并在<ckeditorDirectory>/ckeditor-dev/plugins/myFormat/icons/myFormat.png.