【发布时间】:2018-09-08 23:40:01
【问题描述】:
我正在使用 contenteditable 并尝试创建一个简单的编辑器。不幸的是我不能使用document.execCommand() 并且必须自己实现它。我在这里要做的是,如果用户按下粗体按钮,我想让文本变为粗体。 The code I have written below works, but it only works when the selection is in one node, not multiple nodes.
document.getElementById("bold").onclick = function() {
var selection = document.getSelection(),
range = selection.getRangeAt(0).cloneRange();
range.surroundContents(document.createElement("b"));
selection.removeAllRanges();
selection.addRange(range);
}
<div contenteditable="true" id="div">This is the editor. If you embolden only **this**, it will work. But if you try to embolden **this <i>and this**</i>, it will not work because they are in different nodes</div>
<button id="bold">Bold</button>
我的问题是:有没有一种解决方案,我可以单击粗体,即使它们位于不同的节点中,它也可以使文本加粗?如果是这样,我该怎么做?我正在寻找简单而优雅的东西,但如果它必须很复杂,我会很感激对代码的一些解释。非常感谢。
【问题讨论】:
标签: javascript html contenteditable