【问题标题】:Unwrap selected text from html tag using pure js使用纯js从html标签中解开选定的文本
【发布时间】:2018-09-12 23:53:26
【问题描述】:

我正在使用 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 解决方案和一些优雅而简单的东西,但如果它必须很复杂,我将不胜感激代码的一些解释。非常感谢你。

【问题讨论】:

  • HTML 编辑远非简单。例如,突出显示可能跨越多个段落

标签: javascript html contenteditable


【解决方案1】:

存储创建的元素:

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

要展开,将每个子元素移动到 b 元素之前,然后删除 b 元素:

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

b.parentNode.removeChild(b)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 2011-07-10
    • 2013-04-28
    • 2017-03-31
    相关资源
    最近更新 更多