【问题标题】:CKEditor remove inline img styleCKEditor 移除内联 img 样式
【发布时间】:2013-08-02 12:13:14
【问题描述】:

我正在使用响应式图像技术,通过 CSS 将最大宽度设置为 100%。

这不适用于通过 CKEditor 添加的任何图像,因为添加了内联样式。

在 CSS 中,我添加了一个样式来覆盖宽度,这有效,但 height: auto 无效,因此图像被拉伸了。

我首先需要找到一种方法来阻止 CKEditor 添加内联样式。

我正在使用 CKEditor 4.x

谢谢

【问题讨论】:

    标签: ckeditor


    【解决方案1】:

    比已接受的答案更好的替代方法是使用disallowedContent (see docs),而不是allowedContent

    使用allowedContent 需要您为每个可能的标签或属性创建一个相当大的白名单; disallowedContent 没有;允许您定位要忽略的样式。

    可以这样做:

    CKEDITOR.replace( 'editor1', {
        disallowedContent: 'img{width,height};'
    });
    

    【讨论】:

    • 这应该是公认的答案,因为它完全消除了在弹出窗口中设置图像尺寸的能力......这是您想要的响应。酷。
    • 在 ckeditor 4.6 中不起作用,这里是 config.js pastebin.com/Dre5DskU
    【解决方案2】:

    从 4.1 版开始,CKEditor 提供了所谓的Content Transformations 并且已经定义了其中的一些。如果您在config.allowedContent 中限制您不想在<img> 样式中使用widthheight,那么编辑器会自动将样式转换为属性。例如:

    CKEDITOR.replace( 'editor1', {
        allowedContent: 
            'img[!src,alt,width,height]{float};' + // Note no {width,height}
            'h1 h2 div'
    } );
    

    然后:

    <p><img alt="Saturn V carrying Apollo 11" class="left" src="assets/sample.jpg" style="height:250px; width:200px" /></p>
    

    成为输出:

    <p><img alt="Saturn V carrying Apollo 11" height="250" src="assets/sample.jpg" width="200" /></p>
    

    而且,我猜,它完全解决了你的问题。

    【讨论】:

    • 据我所知,它还应该删除您的 p 标签,因为它们是您的规则不允许的。我想在不需要每个可能的标签和属性的怪物白名单的情况下进行这种转换,即使用allowedContent:true,可能像这样:CKEDITOR.on('instanceReady', function(ev) {ev.editor.filter.addTransformations([['img: sizeToAttribute']]);}); 让它始终将样式转换为属性,但这没有任何作用。
    • 仅供参考 p 由编辑器添加为必备标签,前提是 config.enterModeENTER_P
    • @Synchro 是正确的,使用 allowedContent 需要您将每个标签和属性列入白名单。我已经发布了一个替代的、更合适的解决方案。
    【解决方案3】:

    您可以收听instanceReady 事件并在保存之前更改任何元素,在您的情况下为img 标签

    CKEDITOR.on('instanceReady', function (ev) {
        ev.editor.dataProcessor.htmlFilter.addRules(
        {
            elements:
            {
                $: function (element) {
                    // check for the tag name
                    if (element.name == 'img') {
                        var style = element.attributes.style;
    
                       // remove style tag if it exists
                        if (style) {
                            delete element.attributes.style;
                        }
                    }
    
                    // return element without style attribute
                    return element;
                }
            }
        });
    }); 
    

    【讨论】:

    • 这个解决方案效果很好。当我不想使用allowContent时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多