【发布时间】:2013-08-02 12:13:14
【问题描述】:
我正在使用响应式图像技术,通过 CSS 将最大宽度设置为 100%。
这不适用于通过 CKEditor 添加的任何图像,因为添加了内联样式。
在 CSS 中,我添加了一个样式来覆盖宽度,这有效,但 height: auto 无效,因此图像被拉伸了。
我首先需要找到一种方法来阻止 CKEditor 添加内联样式。
我正在使用 CKEditor 4.x
谢谢
【问题讨论】:
标签: ckeditor
我正在使用响应式图像技术,通过 CSS 将最大宽度设置为 100%。
这不适用于通过 CKEditor 添加的任何图像,因为添加了内联样式。
在 CSS 中,我添加了一个样式来覆盖宽度,这有效,但 height: auto 无效,因此图像被拉伸了。
我首先需要找到一种方法来阻止 CKEditor 添加内联样式。
我正在使用 CKEditor 4.x
谢谢
【问题讨论】:
标签: ckeditor
比已接受的答案更好的替代方法是使用disallowedContent (see docs),而不是allowedContent。
使用allowedContent 需要您为每个可能的标签或属性创建一个相当大的白名单; disallowedContent 没有;允许您定位要忽略的样式。
可以这样做:
CKEDITOR.replace( 'editor1', {
disallowedContent: 'img{width,height};'
});
【讨论】:
从 4.1 版开始,CKEditor 提供了所谓的Content Transformations 并且已经定义了其中的一些。如果您在config.allowedContent 中限制您不想在<img> 样式中使用width 和height,那么编辑器会自动将样式转换为属性。例如:
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.enterMode 是 ENTER_P。
allowedContent 需要您将每个标签和属性列入白名单。我已经发布了一个替代的、更合适的解决方案。
您可以收听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;
}
}
});
});
【讨论】: