2012-09-21 151 views
14

如何動態更改CKEditor工具欄(不使用預定義的工具欄)?動態更改CKEditor工具欄

CKEditor Developer's Guide只告訴你如何在初始化期間設置工具欄。

我使用的是CKEditor 3.6.4。

+2

我猜你總是可以重新初始化整個編輯.. – mb21

回答

9

mb21的建議,我設法重新初始化整個編輯器來加載一個新的工具欄:

CKEDITOR.instances.editor.destroy(); 
CKEDITOR.replace('editor', configWithNewToolbar); 
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)是需要的restablish這些事件偵聽器這樣的工具欄的代碼會重新生成新的工具欄。)

+1

關於你的最後的評論,我認爲這樣的監聽器將自動刪除該代碼可以使用這樣的fireOnce。 – AlfonsoML

1

只是一個快速的一個。

您可能需要加入這一行,如果你的loadToolbar功能[R工具欄包含的文字顏色和/或按鈕的backgroundColor:

//Need to call init for colorbutton so that we can re-draw the color buttons 
CKEDITOR.plugins.registered.colorbutton.init(this); 
6
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); 
1

至少對我來說這有一點複雜....

,並回答了我想我會分享工作中的問題碼。

我有一個用戶定義的文本片段 - 在我需要加載的ckeditor說法中稱爲模板。 我還根據窗口寬度動態更改工具欄,並動態調整窗口大小調整大小。每個瀏覽器大小都有自己的自定義工具欄(XS,SM,MD)。我希望所有具有CKEDITOR的元素都有一個.ckeditor類,並且他們有一個ID分配。 此外,我有一個關於模糊ajax保存處理程序設置,所以失去焦點時,控制會自動保存(通過ajax_post函數),如果需要。

我使用setupCKEdit調用過程。這要歸功於hpique的靈感,即去除舊對象並創建新實例。在resize事件中,我會稍微延遲一次(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 ************** 
3

根據[CKEditor的文檔] [1],他們已經放棄了「主題」,因此「loadToolbar()」上述方法的概念已被修改的位與最新版本的工作CKEditor的。

這爲我工作(CKEditor的4.4.4):

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

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> 
1

或者:

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

    //the configSimple.js file is the same folder with config.js 
0

我假設你想要通過插件文件添加按鈕。這是如何。將你的按鈕添加到用戶界面。

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]]。 [數組[10]表示第一組中有10個按鈕。你可以將你的按鈕推入任何這些數組中。

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' ] }, 
    ]; 
});