15

如何动态更改 CKEditor 工具栏(不使用预定义的工具栏)?

CKEditor Developer's Guide仅告诉您如何在初始化期间设置工具栏。

我正在使用 CKEditor 3.6.4。

4

10 回答 10

10

按照mb21的建议,我设法通过重新初始化整个编辑器来加载新工具栏:

CKEDITOR.instances.editor.destroy();
CKEDITOR.replace('editor', configWithNewToolbar);
于 2012-09-21T13:37:13.843 回答
8
var editor = CKEDITOR.instances['text_id'];
if (editor) { editor.destroy(true); }

CKEDITOR.config.toolbar_Basic = [['Bold','Italic','Underline',
'-','JustifyLeft','JustifyCenter','JustifyRight','-','Undo','Redo']];
CKEDITOR.config.toolbar = 'Basic';
CKEDITOR.config.width=400;
CKEDITOR.config.height=300;
CKEDITOR.replace('text_id', CKEDITOR.config);
于 2013-08-13T12:28:05.310 回答
3

您可以使用以下代码重新加载或更改工具栏,而无需重新加载编辑器:

  CKEDITOR.editor.prototype.loadToolbar = function(tbName) {
    // If the 'themeSpace' event doesn't exist, load the toolbar plugin
    if (!this._.events.themeSpace) {
      CKEDITOR.plugins.registered.toolbar.init(this);
    // causes themeSpace event to be listened to.
    }
    // If a different toolbar was specified use it, otherwise just reload
    if (tbName) this.config.toolbar = tbName;

    // themeSpace event returns a object with the toolbar HTML in it
    var obj = this.fire( 'themeSpace', { space: 'top', html: '' } );

    // Replace the toolbar HTML 
    var tbEleId = "cke_"+this.config.toolbarLocation+"_"+this.name;
    var tbEle = document.getElementById(tbEleId);
    tbEle.innerHTML = obj.html;
  } // end of loadToolbar

在 editor.prototype 中添加函数使其成为任何编辑器实例的方法。您的编辑器对象可能是 CKEDITOR.instances.editor1

loadToolbar 的参数是要加载的工具栏的名称,如果为 null,则重新加载当前工具栏。当前工具栏的名称在 CKEDITOR.instances.editor1.config.toolbar 中。如果您指定工具栏“foo”,则必须有一个定义工具栏内容的 CKEDITOR.instances.editor1.config.toolbar_foo 数组。

您可以从当前工具栏数组变量中添加或删除内容,然后使用以下命令重新加载它: edObj.loadToolbar(null);


(不影响上述方法的元问题:我不明白为什么在编辑器最初加载主题后,'themeSpace' 事件的侦听器消失了。(工具栏插件 init() 方法执行 event.on("themeSpace" ...)但在编辑器初始化后监听消失了。我没有看到它在哪里做了 removeListener()。所以调用 ...toolbar.init(this) 需要重新建立那些事件监听器,所以工具栏代码将重建新的工具栏。)

于 2013-02-03T14:03:08.460 回答
3

根据 [CKEditor 文档][1],他们已经放弃了“主题”的概念,因此必须对上面提到的“loadToolbar()”方法进行一些修改才能与最新版本的 CKEditor 一起使用。

这对我有用(CKEditor 4.4.4):

CKEDITOR.editor.prototype.setToolbar = function(tbName) {
		if (!this._.events.themeSpace) {
		  CKEDITOR.plugins.registered.toolbar.init(this);
		// causes themeSpace event to be listened to.
		}
		// If a different toolbar was specified use it, otherwise just reload
		if (tbName){
			this.config.toolbar = tbName;
		}
		//According to CKEditor documentation
		var obj = this.fire( 'uiSpace', { space: 'top', html: '' } ).html;
		console.log("Received from themespace:");
		console.log(obj);
		// Replace the toolbar HTML 
		var tbEleId = this.id +"_" + this.config.toolbarLocation;
		console.log("Editor element id: " + tbEleId);
		var tbEle = document.getElementById(tbEleId);
		//tbEle.innerHTML = obj.html;
		$(tbEle).html(obj);
      }
[1]:http ://docs.ckeditor.com/#!/guide/dev_api_changes

于 2014-09-19T13:26:02.540 回答
1

只是一个快速的。

如果您的工具栏包含 textcolor 和/或 backgroundcolor 按钮,您可能需要将此行添加到 loadToolbar 函数:

//Need to call init for colorbutton so that we can re-draw the color buttons
CKEDITOR.plugins.registered.colorbutton.init(this);
于 2013-03-15T12:44:27.200 回答
1

至少对我来说这有点复杂......

并回答我认为我会分享工作代码的问题。

我有一个用户定义的文本片段——在我需要加载的 ckeditor 用语中称为模板。我还根据窗口宽度动态更改工具栏,并在窗口调整大小时动态调整大小。每个浏览器尺寸都有自己的自定义工具栏。(XS,SM,MD)。我希望所有带有 CKEDITOR 的元素都有一个 .ckeditor 类,并且它们分配了一个 ID。此外,我设置了一个模糊 ajax 保存处理程序,因此如果需要,当失去焦点时,控件会自动保存(通过 ajax_post 函数)。

我使用 setupCKEdit 调用该过程。感谢 hpique 提供了删除旧对象并创建新实例的灵感。在调整大小事件上,我会稍微延迟(resizeTimeout= 200 毫秒),因此在更改窗口大小时它不会经常触发。

// ********* ck editor section starts **************

var resizeTimeout;
var ckeditorXSToolbar = Array(
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste','-', 'Undo', 'Redo' ] },
    { name: 'document', groups: [ 'mode' ], items: [ 'Source'] },
    { name: 'tools', items: [ 'Maximize'] },
    { name: 'styles', items: [ 'Format', 'Font', 'FontSize'] ,class:'hidden-xs'},
    { name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'TextColor','Bold', 'Italic'] }

);

var ckeditorSMToolbar = [
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize'] ,class:'hidden-xs'},
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    { name: 'editing', groups: [ 'find', 'selection' ], items: [ 'Find', 'Replace', '-', 'SelectAll' ] },
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-', 'Save', 'NewPage', 'Preview', 'Print'] },

    { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'TextColor','Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
    { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] }
];
var ckeditorMDToolbar = [
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize'] ,class:'hidden-xs'},
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-', 'Save', 'NewPage', 'Preview', 'Print'] },

    { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'TextColor','Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe' ] },

    { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
    { name: 'others', items: [ '-' ] },
    { name: 'about', items: [ 'About' ] }
];

function setupCKEdit(selector){
    if (typeof(o.snippets) == 'object'){
        var template = {
            imagesPath:url_img ,
            templates: o.snippets
        };
        CKEDITOR.addTemplates('myTemplate', template);
    }   
    resizeCKEdit();

    $('.ckeditor',selector).not('.hasCKEDITOR').each(function(index,element){
        $(this).addClass('hasCKEDITOR');
        var ckConfig = {
            templates_replaceContent:false,
            scayt_slang:'en_GB',
            scayt_autoStartup:scayt_autoStartup,
            toolbarCanCollapse:true,
            extraPlugins:'templates,colorbutton',
            toolbar:getCKtoolbar(),
            toolbarStartupExpanded:getCKToolbarStartup()
        };
        // inject the snippets after the toolbar[].name = 'document'
        if (typeof(o.snippets) == 'object'){
            ckConfig.templates = 'myTemplate';
            for(var i = 0 ; i < ckConfig.toolbar.length ; i++){
                if (ckConfig.toolbar[i].name == 'document'){
                    // iterate throught each document element to make sure template is not already there.
                    var hasTemplate = false;
                    for ( var j = 0 ; j < ckConfig.toolbar[i].items.length; j++){
                        if (ckConfig.toolbar[i].items[j] == 'Templates'){
                            hasTemplate = true;
                        }
                    }
                    if (hasTemplate == false){
                        ckConfig.toolbar[i].items.push('-'); // add to documents group.
                        ckConfig.toolbar[i].items.push('Templates');
                    }

                }
            }           
        }
        $(this).ckeditor(ckConfig);
        var editor = CKEDITOR.instances[this.id];
        if(typeof(editor) == 'object'){
            editor.on('blur',function(event){
                if (event.editor.checkDirty()){
                    var ta = $('#'+event.editor.name); // ta = textarea
                    if ( (typeof(ta) == 'object')
                        && (typeof(ta[0]) == 'object')
                        && ( $(ta[0]).hasClass('noajax') == false )
                        && ( $(ta[0]).data('id')) 
                        && ( ta[0].name)) {
                        var data = {
                            field_name:ta[0].name,
                            field_value:event.editor.getData(),
                            id:$(ta[0]).data('id')
                            };
                        data[ta[0].name]=event.editor.getData();
                        ajax_post(url_ajax + 'update_field', data);
                        event.editor.resetDirty();
                    }
                }
            });
        }
    });
}
function getCKtoolbar(){
    // returns the CK editor toolbar array based on window width
    var dw = $(document).width();
    if (dw < 768){
        return ckeditorXSToolbar;
    } else if(dw < 991){
        return ckeditorSMToolbar;
    }
    else {
        return ckeditorMDToolbar;
    }
}

function getCKToolbarStartup(){
    // returns the toolbarStartupExpanded parameter, based on window width
    var dw = $(document).width();
    if (dw < 768){
        return false;
    } else if(dw < 991){
        return true;
    }
    else {
        return true;
    }
    return true;
}
function resizeCKEdit(){
    // when there is a document resize, update the toolbar buttons.
    if ($('body').data('resize_enabled') == undefined){
        $('body').data('resize_enabled',true);
        $(window).resize(function(event){
            // only do the reize 100msec after the resizing finishes.
            window.clearTimeout(resizeTimeout);
            resizeTimeout = window.setTimeout(function(){

            // iterate through all CKEDITOR instances, and update their toolbars.
                var ckConfig = {
                    templates_replaceContent:false,
                    scayt_slang:'en_GB',
                    scayt_autoStartup:scayt_autoStartup,
                    toolbarCanCollapse:true,
                    extraPlugins:'templates,colorbutton',
                    toolbar:getCKtoolbar(),
                    toolbarStartupExpanded:getCKToolbarStartup()
                };
                if (CKEDITOR.editor.length){
                    // need to get all instances before deleting them,
                    var instances = Array();
                    var i = 0;
                    for (var instance in CKEDITOR.instances) {
                        instances[i] = instance;
                        i++;
                    }
                    for (i = 0 ; i < instances.length ; i ++){
                        CKEDITOR.instances[instances[i]].destroy();
                        $('#'+instances[i]).removeClass('hasCKEDITOR');
                        setupCKEdit($('#'+instances[i]).parent());
                    }
                }
            },200);

        });
    }
}
// ********* ck editor section ends **************
于 2014-09-19T11:55:13.547 回答
1

或者:

   $(document).ready(function() {
      CKEDITOR.config.customConfig = 'configSimple';
   }); 

   //the configSimple.js file is the same folder with config.js
于 2015-09-01T10:11:30.633 回答
0

如果您想要一种在不同区域交换工具栏的简单方法,您只需将工具栏添加到配置中,然后在实例化编辑器时选择您想要的工具栏。

在 config.js 中:

CKEDITOR.editorConfig = function(config)
{
// default toolbar
config.toolbar = [
    { name: 'source',       items: [ 'ShowBlocks', 'Source' ] },
    { name: 'clipboard',    items: [ 'Undo', 'Redo', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'  ] },
    { name: 'editing',      items: [ 'Find', 'Replace', 'SelectAll', 'Scayt' ] },

    { name: 'p2',           items: [ 'Blockquote', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
    { name: 'links',        items: [ 'Link', 'Unlink', 'Anchor' ] },
    { name: 'paragraph',    items: [ 'NumberedList', 'BulletedList' ] },
    { name: 'insert',       items: [ 'CreatePlaceholder', 'CreateDiv', 'Image', 'Table', 'HorizontalRule', 'SpecialChar', 'Iframe' ] },

    //{ name: 'styles',         items: [ 'Styles', 'Format' ] },
    { name: 'basicstyles',  items: [ 'Bold', 'Italic', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
    { name: 'styles',       items: [ 'Format' ] },
    { name: 'morestyles',   items: [ 'Font', 'FontSize' ] },
    { name: 'colors',       items: [ 'BGColor', 'TextColor' ] }
];

// here is one custom toolbar
config.toolbar_mycustom1 = [
    { name: 'source',       items: [ 'ShowBlocks', 'Source' ] },
    { name: 'clipboard',    items: [ 'Undo', 'Redo', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'  ] },
    { name: 'editing',      items: [ 'Find', 'Replace', 'SelectAll', 'Scayt' ] }
];

// here is another custom toolbar
config.toolbar_mycustom2 = [
    { name: 'styles',       items: [ 'Format' ] },
    { name: 'morestyles',   items: [ 'Font', 'FontSize' ] },
    { name: 'colors',       items: [ 'BGColor', 'TextColor' ] }
];

// ...other config vars here

在您实例化编辑器实例的页面中,这样做:

<script>
    CKEDITOR.replace('MyObject', {toolbar: 'mycustom2'});
</script>
于 2014-12-29T00:02:28.010 回答
0

您可以根据需要动态创建工具栏。我发现最好的方法是监听关于实例创建的 CKE 事件。

CKEDITOR.on('instanceCreated', function(event) {
    var editor = event.editor;
    editor.config.toolbar = [
        { name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'Bold', 'Italic','Subscript', 'Superscript' ] },
    ]; // could be from synchronous!!! XHR as well 
});

CKEDITOR.on('instanceReady', function(event) {
    var editor = event.editor;
    editor.config.toolbar = [
        { name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'Bold', 'Italic','Subscript', 'Superscript' ] },
    ];
});
于 2016-05-25T09:01:39.760 回答
0

我假设您想通过插件文件添加按钮。这里是如何。将按钮添加到 ui。

editor.ui.addButton('ButtonName', {
  label: lang.lockediting.locked,
  icon: this.path + 'icons/locked.png',
  command: 'lockediting'});

然后您可以将 ButtonName 推送到工具栏。

//Here it is pushed as a new group
editor.config.toolbar.push(['ButtonName']);

如果你检查 console.log(editor.config.toolbar); 您将看到工具栏是一个对象,其工具栏组为数组 [Array[10]、Array[2]、Array[5]]。[Array[10] 表示第一组有 10 个按钮。您可以将按钮推入任何这些阵列。

于 2015-10-26T03:58:24.843 回答