首页 > 解决方案 > 当您在方法上有编辑器时,TinyMCE 更新工具栏(初始化后)

问题描述

我正在为 WordPress 开发 Google Fonts 插件,并尝试获得与核心 WYSIWYG 编辑器相同的效果。基本上,当您单击带有字体类的元素(在编辑器内)时,我想获取该类,然后基于该类重新加载工具栏中的字体系列/样式列表框。

(我在 SO 上发现了一些技巧,比如在 TinyMCE 中初始化后修改工具栏的正确方法,但没有像 WP 核心示例那样有效)

当你点击P,H1,H3,H3时有相同的功能......他们是怎么做到的?你能至少指出我在 WordPress 发行版中的 JS 文件吗?如果看到代码,我想我可以弄清楚。

这是演示我在说什么的 GIF。提前致谢。

在此处输入图像描述

标签: javascriptwordpresstinymce

解决方案


我找到了解决方案,因为它不是一个 hack,就像我在 SO 上找到的其他解决方案一样,我将它发布在这里并希望它可以帮助其他试图做类似事情的人。

首先要访问按钮/列表框需要使用带有回调函数的 onpostrender。

editor.addButton( 'developry_google_font_family_button', {
   type  : 'listbox',
   onpostrender : fontFamilyNodeChange,
   value : '',
...

接下来回调函数应如下所示:

function fontFamilyNodeChange() {
    var listbox = this;
    editor.on('NodeChange', function( e ) {
        // This next part is specific for my needs but I will post it as an example.
        var selected = [];
        if ( $( e.element ).hasClass( 'mce-ga' ) )  { // this a class I add to all elements that have google fonts format
            // Then I strip the classes from classList that I don't need and add the rest into an array (e.g ['roboto', '100'])
            var gfont_options = $( e.element ).attr('class')
                .replace('mce-ga', '')
                    .replace('mce-family-', '')
                        .replace('mce-weight-', '')
                            .trim()
                                .split(' ');
            selected.push( gfont_options );
            // At end I add the new value to listbox select[0][0] (e.g. 'roboto')
            listbox.value(selected[0][0]);
        }
    });
}

这是一个例子:

在此处输入图像描述


推荐阅读