回到顶部

阅读目录

CKEditor 禁止 img 标签自动添加 style 样式 - 禁止自动设置 width 和 height

出处:https://shiyousan.com/post/636253649204480535

 

在使用CKEditor的过程中发现,每次上传或添加图片的时候,总会 自动给img 标签添加 width 和 height 的 style 内联样式。由于网站本身对图片有进行自适应处理(添加了自适应的CSS),所以image插件的这种行为无异于画蛇添足。后来研究了下,找到了在CKEditor中禁止img自动添加宽高的方法!通过官方提供的 disallowedContent 属性可以解决这个问题!

这里先上个图说明下情况,可以看到CKEditor的image插件在你添加或上传图片的时候,会自动计算图片的宽高,然后在图像属性对话框中给你自动填上(假设图片宽520px,高度609px):

再查看下源码,就会发现插件已经给img标签添加了内联样式代码:style="height:609px; width:520px"

因为我完全不需要这部分冗余的代码,所以必须让插件不再自动添加宽高属性。经常手动删除这些代码还是比较烦人的,好在插件本身有提供内容过滤功能,通过设置disallowedContent属性的相应规则,可以在CKEditor中强制禁用相应的HTML内容,包括元素以及其属性、类(class)、内联样式(style)等等,强烈建议看官方文档,有详细DEMO演示

此外disallowedContent属性不仅可以在全局进行设置,也可以在调用CKEditor的时候单独设置(也就是创建CKEditor实例/对象的时候)。

这里结合我的情况说明下如何设置。首先是全局设置,在ckeditor中的config.js文件中,找到editorConfig并设置disallowedContent属性

/**
 * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';

    // 添加插件,多个插件用逗号隔开
    config.extraPlugins = 'codesnippet';
    // 设置高亮风格, 如果不设置着默认风格为default
    config.codeSnippet_theme = 'monokai_sublime';
    // 全局禁止自动设置图片 width 和 height
    config.disallowedContent = 'img{width,height};img[width,height]';
};

 

如果此功能只需要在单独几个页面模块中用,那么在创建实例的方法 replace 里传入参数即可:(未验证是否可用,在编辑器提示错误)

CKEDITOR.replace(
    "ckeditorId", {
        disallowedContent: 'img{width,height};img[width,height];'
    }
);

上面两种方式都可以实现在CKEditor中强制禁用img标签的style以及widht/height属性,这样文本编辑器中就不会出现冗余的代码,会被插件自动去除。另外额外提下,测试的时候要注意删除缓存,否则看不出修改的效果!

再说一个注意事项,disallowedContent属性只有在CKEditor 4.4以上的版本才有,对于老版本我就没办法了,也懒得去研究了。这里先看官方文档的这段说明:

The Disallowed Content feature was introduced in CKEditor 4.4 as a part of the Advanced Content Filter system which was introduced in CKEditor 4.1.

按照上面文档说明,这部分功能其实是属于CKEditor提供的高级内容过滤,disallowedContent就是黑名单模式,可以禁用和去除你不想出现在CKEditor编辑器中的HTML标签/属性/内联样式等代码。就像我遇到的情况,就是要禁用img标签的width和height内联样式,防止与自定义的class产生冲突,也让代码看上去更加简洁干净!

当然也有对应的白名单模式:allowedContent属性。高级内容过滤器的功能貌似在4.1版本的时候就有了,但是没有黑白名单的功能,我英文不好也看不太懂,反正用4.4的就对了。

最后贴下灵感来源,主要还是从stackoverflow中得到了思路:CKEditor remove inline img style

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!

前一篇: ckeditor 上传图片后,怎么让链接选项卡 自动添加图片地址(已解决)
下一篇: Linux scp 无密码复制文件
captcha