使用 document.execCommand('insertHTML' 在 contentEditable 中插入 span

Insert span in contentEditable with document.execCommand('insertHTML',

我正在开发富内容编辑器。配置设置为添加 <p> 标记作为段落分隔符:

document.execCommand('defaultParagraphSeparator', false, "p");

我必须插入特殊的 <span contenteditable='false'> 部分:

document.execCommand('insertHTML', false, "<span contenteditable='false'>...</span>");

插入未按预期完成。

我预计:

<p>something <span>...</span></p>

我得到了:

<p>something </p>
<span>...</span>

我想不通为什么 span 标签没有插入到 p 标签中。有什么想法吗?

execCommand 在不同浏览器之间存在不一致和错误的历史。如今,execCommand 已过时:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

来源:https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

我建议您阅读有关最佳选择的页面:https://medium.com/@jitubutwal144/three-different-ways-to-build-inline-content-editor-using-javascrpit-d58c2edac9cb