单击“自定义格式”文本时,TinyMCE 4.0+“自定义按钮”处于活动状态和非活动状态

Ant*_*ius 4 onclick button tinymce-4

我在tinyMCE 4.0+中添加了一个自定义按钮/插件,该格式使用特定标签阻止了我的文本。例如:<h1>my clicked text</h1>。除了按钮不会激活外,其他所有功能都很好。当它确实激活时,当我单击已经格式化的文本时,它也不会激活(就像单击粗体按钮时的“粗体”按钮一样)。

由于有来自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');
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

我希望这可以节省您无数令人沮丧的时间!!!

ilP*_*tiz 5

这正是我想要的!(但是,我花了几个令人沮丧的时间试图到达那里:P)

只是想记下我发现的一种更可靠和通用的方法来识别按钮,以摆脱第28个按钮的定制。

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