在带有Image2插件的CkEditor 4.3中,更改图像src的正确方法是什么?

时间:2013-12-21 16:18:13

标签: javascript jquery image ckeditor

正如标题所说,我使用的是基于完整软件包的CkEditor 4.3版本,其中还包含Image2 plugin(使用CkBuilder构建,以便自动解决每一个依赖)。

我需要的是以编程方式(使用,如果需要,还使用jQuery)更改图像的src属性。

使用经典Image plugin,我使用以下代码执行此操作:

var imgToBeReplaced = editor.document.findOne("img#myImg");
imgToBeReplaced.setAttribute("src", newSrc);

因为我需要确保编辑器对象的getData()方法返回正确的数据,所以我还要执行以下操作(了解更多信息:CKEditor - Change image source):

$(imgToBeReplaced.$).attr("data-cke-saved-src", newSrc);

当我使用Image2 plugin执行此操作时,图像已正确更改,但之后,我无法调整其大小,也无法访问图像属性(双击图像,也不使用右键单击图像打开的上下文菜单,因为“属性”选项不再存在。

所以,问题是:如何才能正确更改src(和data-cke-saved-src)属性,而不会失去更改图像属性的可能性?

1 个答案:

答案 0 :(得分:2)

现在使用小部件,您唯一需要担心的是

  • 获取正确的小部件实例
  • 调用setData()方法

至于这个特殊情况,你需要

// You need to have CKEDITOR.editor instance, here i will pick it from instances property.
var editor = CKEDITOR.instances.editor1,
    // All widgets instances are stored here, we will iterate on top of them.
    widgets = editor.widgets.instances,
    curWidget,
    i;

for ( i in widgets ) {
    curWidget = widgets[ i ];
    // Ensure that image is a part of widget, and src matchs our needs.
    if ( curWidget.definition.name == 'image2' && curWidget.parts.image.getAttribute( 'src' ) == 'assets/image1.jpg' ) {
        // Update src attribute.
        curWidget.setData( 'src', 'http://upload.wikimedia.org/wikipedia/en/1/18/Unicorn-head-circle-2.png' );
    }
}

这是更新 image2 src的正确方法 - 所有内容都将由image2插件本身处理。