我有以下代码在当前位置插入文本:
editor.model.change( writer => {
                    editor.model.insertContent( writer.createText('[Insert]') );
                });
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下都可以正常工作,例如插入段落或标题中。给出的例子:
前:
<h2>Sample</h2>
Run Code Online (Sandbox Code Playgroud)
插入后:
<h2>Samp[Insert]le</h2>
Run Code Online (Sandbox Code Playgroud)
但是如果文本是预先格式化的,例如使用自定义字体大小,它会破坏 html 元素:
前:
<p><span class="text-huge">Sample formatted text</span></p>
Run Code Online (Sandbox Code Playgroud)
插入后:
<p><span class="text-huge">Sample fo</span>[Insert]<span class="text-huge">rmatted text</span></p>
Run Code Online (Sandbox Code Playgroud)
请注意,元素被拆分并插入文本而不应用自定义样式。[插入] 设置在两个跨度之间...
如何在不修改html结构的情况下直接插入文本?
发生这种情况是因为创建的文本节点没有设置属性。为此,您需要获取当前选择的属性并将其传递给该writer.createText()方法。然后创建的文本节点将具有这些属性:
const model = editor.model;
model.change( writer => {
    const currentAttributes = model.document.selection.getAttributes();
    model.insertContent( writer.createText( '[Foo]', currentAttributes ) );
} );
Run Code Online (Sandbox Code Playgroud)
或者,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 );
} );
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           921 次  |  
        
|   最近记录:  |