繁体   English   中英

强制CKEditor向Image2小部件添加类

[英]Force CKEditor to add a class to Image2 widget

我想配置CKEditor(版本4.3.2)为内容中的每个Image2小部件 Figure标签添加一个类属性。 我使用以下代码(基于如何在CKEditor中的段落中添加CSS类和ID? ):

CKEDITOR.on("instanceReady", function(e)
{
    var editor = e.editor;


    pClass = 'additional_class',
    pClassRegexp = new RegExp(pClass, 'g');

    editor.dataProcessor.htmlFilter.addRules(
    {
        elements:
        {
            figure: function(element)
            {
                // If there's no class, assign the custom one:
                if (!element.attributes['class'])
                    element.attributes['class'] = pClass;

                // It there's some other class, append the custom one:
                else if (!element.attributes['class'].match(pClassRegexp))
                    element.attributes['class'] += ' ' + pClass;
            }
        }
    });
});

不幸的是,我只能为没有类“标题”的图形元素添加类,但是它不再是小部件。

您可以使用某些配置选项在CKEditor 4.4及更高版本中执行此操作。 这是CKEditor的image2文档中的相关说明:

多亏了CKEditor 4.4中引入的CKEDITOR.config.image2_alignClasses选项,您可以使用CSS类来设置图像对齐方式。 此外,CKEDITOR.config.image2_captionedClass选项允许您将自定义类分配给字幕图像的元素。

config.image2_alignClasses = [ 'image-left', 'image-center', 'image-right' ];
config.image2_captionedClass = 'image-captioned';

将产生类驱动的,可样式化的标记,使您可以避免使用不灵活且非语义的内联CSS代码:

<figure class="image-captioned image-right">
    <img alt="MyImage" src="myimage.png" />
    <figcaption>MyCaption</figcaption>
</figure>

这会将类添加到现有或新图像

CKEDITOR.on("instanceCreated", function (ev) {
    "use strict";
    ev.editor.on("widgetDefinition", function (evt) {
        var widgetData = evt.data;

        if (widgetData.name !== "image" || widgetData.dialog !== "image2") return;

        //Override of upcast
        if (!widgetData.stdUpcast) {
                widgetData.stdUpcast = widgetData.upcast;

                widgetData.upcast = function (el, data) {
                    el = widgetData.stdUpcast(el, data);

                    if (!el) return el;

                    if (el.name === "img") {
                        el.addClass('img-fluid img-responsive');                                    
                    }

                    return el;
                };
        }

        //Override of downcast
        if (!widgetData.stdDowncast) {
            widgetData.stdDowncast = widgetData.downcast;

            widgetData.downcast = function (el) {

                el = this.stdDowncast(el);

                if (el && el.name === "img") {
                    el.addClass('img-fluid img-responsive');                                    
                }

                return el;
            }
        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM