2014-10-27 85 views
3

我向tinyMCE 4.0+添加了自定義按鈕/插件,其格式使用特定標記鎖定了我的文本。例如:<h1>my clicked text</h1>。除了按鈕不會激活的事實以外,一切都很好。當它激活時,當我點擊已經格式化的文本時(如粗體按鈕在點擊粗體文本時的效果),它將不會激活。TinyMCE 4.0+自定義按鈕在點擊「自定義格式」文本時處於活動狀態並且處於非活動狀態

感謝來自Stackoverflow的無數建議,以及由於完全缺乏適當的解決方案(這裏和tinyMCE文檔),我想在此發佈解決方案。雖然你可以添加你喜歡的話,在這個例子的目的,任何標籤,我要補充<h1>標籤:

//Add the plugin to tinyMCE.init 
tinymce.init({ 
    selector: \"div.editable\", 
    inline: true, 
    plugins: 'addh1s' 
    toolbar: 'addh1s' 
//etc... 
}); 

//Then create a folder entitled, 'addh1s' in the tinyMCE 'plugins' folder 
//and add the plugin.min.js file that contains the following code. 
//*Please note that the number '27' below is the number in order of the 
//'addh1s' button on my tinyMCE toolbar. In your case it can be the 
//number of where your button appears on your toolbar. 

tinymce.PluginManager.add('addh1s', function(editor, url) { 
    editor.addButton('addh1s', { 
     title: 'Add H1 tags', 
     image: '../images/h1.png', 
     onPostRender: function() { 
      editor.on('NodeChange', function(e) { 
       if (editor.formatter.match('h1')) { 
       tinymce.activeEditor.theme.panel.find('toolbar *')[27].active(true); 
       } 
       else { 
       tinymce.activeEditor.theme.panel.find('toolbar *')[27].active(false); 
       } 
      }); 
      }, 
     onclick: function() { 
      tinyMCE.activeEditor.execCommand('FormatBlock', false, 'h1'); 
     } 
    }); 

}); 

我希望這可以節省你無數令人沮喪小時!

回答

3

這正是我一直在尋找的! (然而我花了幾個小時試圖到達那裏:P)

只是想記下一個更可靠和通用的方式,我發現確定的按鈕,擺脫了第28按鈕的定製。

onPostRender: function() { 
    var _this = this; // reference to the button itself 
    editor.on('NodeChange', function(e) { 
     _this.active(editor.formatter.match('h1')); 
    }) 
} 
+0

嘿感謝@ilPittiz,它是這樣的原因,我喜歡這個論壇 – Antonius 2015-06-20 18:25:05

+0

@LucisFeris你應該接受答案 – 2015-12-16 23:46:56

0

我想用元素的類而不是它的節點類型來做到這一點。 這裏是我的解決方案(使用jQuery的,這已經是包括 - 這是一個WordPress版本)

 ed.addButton('add_top_margin',{ 
      title : 'Add extra margin to the top of this element', 
      text : 'Add Top Margin', 
      onclick : function(){ 
       ed.dom.toggleClass(ed.selection.getNode(), 'top_margin'); 
       this.active(!this.active()); //toggle the button too 
      }, 
      onPostRender: function() { 
       var _this = this; // reference to the button itself 
       ed.on('NodeChange', function(e) { 
        //activate the button if this parent has this class 
        var is_active = jQuery(ed.selection.getNode()).hasClass('top_margin'); 
        _this.active(is_active); 
       }) 
      } 
     }) 

和CSS:

.top_margin{ 
    margin-top: 1rem; 
} 
+1

感謝@Mike,我喜歡這個網頁的去向......很難爲tinyMCE找到可靠的解決方案,有時候......希望這個網頁能幫助一些人。 – Antonius 2016-03-05 09:00:43

相關問題