CKEditor删除内联img样式

时间:2013-08-02 12:13:15

标签: ckeditor

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

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

在CSS中,我添加了一种覆盖宽度的样式,但是高度:自动没有,所以图像被拉伸。

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

我正在使用CKEditor 4.x

谢谢

3 个答案:

答案 0 :(得分:14)

对于接受的答案,更好的替代方法是使用disallowedContentsee docs),而不是allowedContent

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

这可以这样做:

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

答案 1 :(得分:8)

从版本4.1开始,CKEditor提供了所谓的Content Transformations,并且已经定义了其中的一些。如果您限制config.allowedContent width中不希望height<img> 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>

成为输出:

{{1}}

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

答案 2 :(得分:2)

您可以在保存之前收听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;
            }
        }
    });
});