首页 > 解决方案 > 如何在 CKEditor 5 的自定义元素中插入带有标题的图像?

问题描述

我正在尝试在自定义标签中插入图像元素。但图像设置不正确。我自定义了ckeditor的图片上传插件。

原始上传插件有以下几行:

const imageElement = writer.createElement('image', { uploadId: loader.id });
const insertAtSelection = findOptimalInsertionPosition(doc.selection);
editor.model.insertContent(imageElement, insertAtSelection);

它在 dom 树中添加图像,如下所示:

<h2>TITLE</h2>
<figure class="image ck-widget ck-widget_selected" contenteditable="false">
    <img src="EXAMPLE/URL" title="" style="">
    <figcaption class="ck-editor__editable ck-editor__nested-editable ck-placeholder" contenteditable="true" data-placeholder=""><br data-cke-filler="true"></figcaption>
</figure>

我改变了插件。当我上传图片时,此代码行正在运行:

const imageElement = writer.createElement('image', { uploadId: loader.id });
writer.appendElement('content', { 'guid': guid }, parent);
content = parent.getChild(parent.childCount - 1);
writer.append(imageElement, content);
writer.setSelection(content.getChild(content.childCount - 1), 0);

我的代码将图像插入到 dom 树,如下所示:

<h2>TITLE</h2>
<content>
    <figure class="image ck-widget" contenteditable="false">
        <img>
    </figure>
</content>

如何设置图像属性和标题?我怀疑insertContent. 我试图运行insertContent,但我不知道应该发送什么insertContent作为位置参数。如果我使用findOptimalInsertionPosition(doc.selection),图像会添加到<content>.

标签: javascriptckeditorckeditor5

解决方案


定义架构

首先,您需要确保<image>在您的自定义模型元素中允许这样做。如果您像这样注册它:

editor.model.schema.register( 'custom', {
    allowContentOf: '$root',
    allowWhere: '$block'
} );

那你就好了。既然<$root>允许<image>在里面,你<custom>就会允许<image>

您可以在Schema deep dive guide中阅读有关编写模式规则的更多信息。

模型结构

现在,您问如何设置图像的标题。要理解这一点,您需要询问模型中图像的结构是什么。答案将是 - 它与您在视图中看到的非常不同:

<image src="...">
    <caption>Caption text</caption>
</image>

这就是您要创建的结构,以便插入带有标题的图像。

在给定位置插入图像

插入任意内容的最佳方法是editor.model.insertContent()因为它需要处理两件事:

  • 插入后将文档选择设置为所需的(至少,从类似粘贴的情况)位置,
  • 确保它插入的内容插入到架构允许的位置(这就是我们需要先配置架构的原因)。

模型编写器方法不做这些事情,所以除非你确切地知道应该在哪里插入图像以及你想如何设置选择,否则不要使用它们。

那么,如何使用insertContent()呢?

editor.model.change( writer => {
    const image = writer.createElement( 'image', { src: '...' } );
    const caption = writer.createElement( 'caption' );

    writer.appendText( 'Caption text', caption );
    writer.append( caption, image );


    // Option 1: If you have the <custom> element by reference:
    const positionInCustom = Position.createAt( customElement, 0 );

    editor.model.insertContent( image, positionInCustom );

    // In this case, we still have to set the selection because we haven't
    // passed document selection to `insertContent()` but a specific position.
    writer.setSelection( image, 'on' );


    // Option 2: Assuming that the document selection is somewhere
    // in your <custom> element you might do this (image will be inserted
    // at the document selection position):

    editor.model.insertContent( image );
} );

editor.model.insertContent()有关可以使用它的各种方式的更多信息,请参阅文档。


推荐阅读