CKEditor5 在不破坏当前元素的情况下插入文本

CKEditor5 Insert Text without breaking current element

我有以下代码在当前位置插入文本:

editor.model.change( writer => {
                    editor.model.insertContent( writer.createText('[Insert]') );
                });

这在大多数情况下都可以正常工作,例如在段落或标题中插入。 给出的例子:

之前:

<h2>Sample</h2>

插入后:

<h2>Samp[Insert]le</h2>



但是如果文本是预先格式化的,例如使用自定义字体大小,它会破坏 html 元素:

之前:

<p><span class="text-huge">Sample formatted text</span></p>

插入后:

<p><span class="text-huge">Sample fo</span>[Insert]<span class="text-huge">rmatted text</span></p>

请注意,元素已拆分,插入的文本未应用自定义样式。 [插入]设置在两个跨度之间...

如何在不修改 html 结构的情况下直接插入文本?

发生这种情况是因为创建的文本节点没有设置属性。为此,您需要 get current selection's attributes and pass it to the writer.createText() 方法。然后创建的文本节点将具有这些属性:

const model = editor.model;

model.change( writer => {
    const currentAttributes = model.document.selection.getAttributes();

    model.insertContent( writer.createText( '[Foo]', currentAttributes ) );
} );

或者,如果您要插入文本,您可以使用 writer.insertText() 方法:

editor.model.change( writer => {
    const selection = editor.model.document.selection;

    const currentAttributes = selection.getAttributes();
    const insertPosition = selection.focus;

    writer.insertText( '[Foo]', currentAttributes, insertPosition );
} );