如何将SVG精灵添加到TinyMCE按钮?

时间:2017-08-23 15:31:33

标签: javascript svg tinymce tinymce-4

我已经为TinyMCE添加了一些自定义工具栏选项,我想为它的图标使用SVG精灵。默认情况下,TinyMCE仅允许“文本”,“图标”或“图像”来设置图标。理想情况下,会有一个“html”选项,我可以在其中输入我的SVG代码,但不会看到它是一个。

如何将SVG精灵添加到TinyMCE按钮?

SVG-sprites.svg

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
    <symbol id="ic_spoiler" viewBox="0 0 24 24">
        <path d="M12,2A9,9 0 0,0 3,11V22L6,19L9,22L12,19L15,22L18,19L21,22V11A9,9 0 0,0 12,2M9,8A2,2 0 0,1 11,10A2,2 0 0,1 9,12A2,2 0 0,1 7,10A2,2 0 0,1 9,8M15,8A2,2 0 0,1 17,10A2,2 0 0,1 15,12A2,2 0 0,1 13,10A2,2 0 0,1 15,8Z" />
    </symbol>
</svg>

主编plugin.js

// Function to create SVG html
var iconSVG = function(name, size) {        
    return '<svg xmlns="http://www.w3.org/2000/svg" height="' + size + '" width="' + size + '" class="' + name + '"><use xlink:href="' + siteURL + '/images/svg-sprite.svg#' + name + '" /></svg>';     
}

// Spoiler Button
tinymce.create('tinymce.plugins.spoiler', {

    init : function(ed, url) {
        ed.addButton('spoiler', {
            /*
            What I want:
            html: iconSVG('ic_spoiler', 20),

            Doesnt work:
            text: iconSVG('ic_spoiler', 20),
            image: iconSVG('ic_spoiler', 20),
            icon: iconSVG('ic_spoiler', 20),
            */
            title : 'Add a Spoiler'
            onclick : function() {
                 ed.selection.setContent('[spoiler]' + ed.selection.getContent() + '[/spoiler]'); 
            }
        });
    },
    createControl : function(n, cm) {
        return null;
    },
});

tinymce.PluginManager.add('spoiler', tinymce.plugins.spoiler);

1 个答案:

答案 0 :(得分:3)

选择了一个相当简单的解决方案。渲染TinyMCE后,使用onPostRender触发一个用SVG图标替换标记的函数。

// Spoiler Button
tinymce.create('tinymce.plugins.spoiler', {

    init : function(ed, url) {
        ed.addButton('spoiler', {
            icon: 'spoiler',
            title : 'Add a Spoiler'
            onClick : function() {
                 ed.selection.setContent('[spoiler]' + ed.selection.getContent() + '[/spoiler]'); 
            },
            onPostRender: function() {
                $('.mce-i-spoiler').replaceWith(iconSVG('ic_spoiler', 20));
            }
        });
    },
    createControl : function(n, cm) {
        return null;
    },
});

tinymce.PluginManager.add('spoiler', tinymce.plugins.spoiler);