CKEditor:插入图像时自定义HTML

时间:2012-06-02 12:35:15

标签: html image ckeditor

我正在使用CKEditor作为我网站的富文本编辑器。在该网站上,我还有一个自定义图像管理器,我在CKEditor中使用“filebrowserImageBrowseUrl”配置参数。 这会在图像属性中放置一个“浏览服务器”按钮,让我从图像管理器中选择一个文件。这很好用。

但是,当我从图像管理器插入图像并在CKEditor中调整大小时,这只会向img标记添加一个样式属性。当人们浏览我的网站时,他们会将图像看作我想要的尺寸,但他们也必须下载大量数据,即使图像尺寸只是缩略图。

当您将宽度和高度作为查询字符串添加到图片网址时,我的图片管理器会自动调整大小。

如何覆盖CKEditor创建的img标记,以便将选定的宽度和高度作为查询变量放入img标记中的src属性以及style属性(以便CKEditor仍然知道图像的大小) ?

我确实在这里发现了另一个问题:CKEditor: Customized HTML on inserting an image 但该问题的答案似乎不起作用,因为该示例的宽度和高度包含图像的原始大小而不是自定义大小。我还调试了这些方法中的各种变量而没有找到自定义大小。

所以问题仍然存在:如何覆盖CKEditor的输出HTML以将图像的大小作为查询变量以及CKEditor默认放置的样式属性?

更新

为了使下面的所有评论更加全面,这里是一个精简版:

CKEDITOR.on('instanceReady', function (ev) {
    var editor = ev.editor,
        dataProcessor = editor.dataProcessor,
        htmlFilter = dataProcessor && dataProcessor.htmlFilter;

    htmlFilter.addRules( {
        elements : {
            $ : function( element ) {
                // Output dimensions of images as width and height attributes on src
                if ( element.name == 'img' ) {
                    var style = element.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];

                        var imgsrc = element.attributes.src + "?width=" + width + "&height=" + height;

                        element.attributes.src = imgsrc;
                        element.attributes['data-cke-saved-src'] = imgsrc;
                    }
                }
            }
        }
    });
});

只要CKEditor生成实际的HTML,就会运行此代码,当您通过单击“源”按钮查看源或通过执行该页的HTTP POST时会发生这种情况。

但是,这是一个小小的警告。上面的代码将继续为“源”按钮或每个回发的每次单击附加宽度和高度查询字符串,因此您可能需要添加一些额外的逻辑来过滤掉宽度和高度查询字符串,然后将它们附加到src属性。

1 个答案:

答案 0 :(得分:2)

如果您查看CKEditor副本中的Output HTML sample,您可以看到它如何使用htmlFilter更改图像以将尺寸放在属性中。根据该代码,您可以编写自己的代码,以便更改图像的URL。

请注意:URL受到保护以避免浏览器出现问题,因此修改“src”属性可能还不够。查看要修改的对象的属性。

相关问题