让 CKEditor 图片响应式(responsive)

通过 CKEditor 上传并插入图片后,CKEditor 的图片部件(widget)会在图片的 <img> 元素里插入行内样式定义来设置图片的宽高,这会导致响应式布局失效:图片因为被固定了宽高,在窗口缩小后会超出外层元素。生成的 HTML 代码示例如下:

<img alt="hello" src="/images/hello.jpg" style="height:300px; width:500px" />

对于这个问题,有三种解决方法:

方法 1:设置 CSS

最简单的解决方法是在 CSS 文件里加入下面的代码:

img {
    max-width: 100%;
    height: auto !important;
}

这会重写 CKEditor 生成的行内 CSS。

方法 2:使用插件 Enhanced Image

你可以使用加强版的图片部件插件 Enhanced Image(Image2)来替代原有的图片部件,同时确保 CKEditor 的版本大于 4.3。

(未测试。)

方法 3:使用 JavaScript

如果你使用 Bootstrap,这里还有另一种方法:

CKEDITOR.on('instanceReady', function (ev) {
    ev.editor.dataProcessor.htmlFilter.addRules( {
        elements : {
            img: function( el ) {
                // Add bootstrap "img-responsive" class to each inserted image
                el.addClass('img-responsive');
        
                // Remove inline "height" and "width" styles and
                // replace them with their attribute counterparts.
                // This ensures that the 'img-responsive' class works
                var style = el.attributes.style;
        
                if (style) {
                    // Get the width from the style.
                    var match = /(?:^|\s)width\s*:\s*(\d+)px/i.exec(style),
                        width = match && match[1];
        
                    // Get the height from the style.
                    match = /(?:^|\s)height\s*:\s*(\d+)px/i.exec(style);
                    var height = match && match[1];
        
                    // Replace the width
                    if (width) {
                        el.attributes.style = el.attributes.style.replace(/(?:^|\s)width\s*:\s*(\d+)px;?/i, '');
                        el.attributes.width = width;
                    }
        
                    // Replace the height
                    if (height) {
                        el.attributes.style = el.attributes.style.replace(/(?:^|\s)height\s*:\s*(\d+)px;?/i, '');
                        el.attributes.height = height;
                    }
                }
        
                // Remove the style tag if it is empty
                if (!el.attributes.style)
                    delete el.attributes.style;
            }
        }
    });
});

出处地址

需要注意的是,如果你使用 Bootstrap 4,需要把第 6 行的 img-responsive 换成 img-fluid。

(未测试。)

撰写评论

电子邮件地址不会被公开,必填项已用 * 标出。