如何在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>之外。

定义模式

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

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

那你就没事了。由于<$root>允许<image>进入,您的<custom>将允许<image>

您可以在模式深入研究指南中阅读更多关于编写模式规则的内容。

模型结构

现在,您询问了如何设置图像的标题。要理解这一点,你需要问模型中图像的结构是什么。答案是——这与你所看到的截然不同:

<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()文档。

最新更新