TinyMCE 4.0+ 自定义按钮在单击文本时处于活动状态和非活动'Custom Formatted'



我在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');
        }
    });
});

我希望这能为你节省无数沮丧的时间!!!

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

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

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

我想用元素的类而不是它的节点类型来实现这一点。这是我的解决方案(使用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;
}

最新更新