首页 文章

CKEditor:插入图像时自定义HTML

提问于
浏览
2

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

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

将宽度和高度作为查询字符串放入图像URL时,我的图像管理器会自动调整大小 .

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

我确实在这里发现了另一个问题:CKEditor: Customized HTML on inserting an image但是这个问题的答案并不是原始大小而是自定义大小 . 我还调试了这些方法中的各种变量而没有找到自定义大小 .

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

UPDATE

为了使下面的所有评论更全面,这里是一个浓缩版本:

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 回答

  • 2

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

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

相关问题