使用纯js从html标签中打开选定的文本

问题描述 投票:2回答:1

我正在使用javascript中使用contenteditable的简单文本编辑器。不幸的是,我不能使用document.execCommand并且必须自己实现它。我创建了一个使我的文字变粗的功能。这是功能:

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 id="editor" contenteditable="true">This is the contenteditable</div>
<button id="bold">Bold</button>

现在,当用户在文本已经是粗体时单击粗体按钮时,我想要取消插入文本。换句话说,我希望文本不再是粗体。

我怎样才能做到这一点?有没有像range.surroundContents或类似的东西?

请注意,我只想将所选文本展开,而不是文档中的每个粗体文本,因此jQuery的unwrap()可能无法正常工作。我正在寻找一个优雅而简单的Vanilla js解决方案,但如果它必须复杂,我会很感激代码的一些解释。非常感谢你。

javascript html contenteditable
1个回答
0
投票

存储创建的元素:

let b = document.createElement("b");
range.surroundContents(b);

要解包,将每个子项移动到b元素之前,然后删除b元素:

while (b.firstChild) {
    b.parentNode.insertBefore(b.firstChild, b)
}

b.parentNode.removeChild(b)
© www.soinside.com 2019 - 2024. All rights reserved.