gpt4 book ai didi

javascript - 使用纯 js 从 html 标签中解包选定的文本

转载 作者:行者123 更新时间:2023-11-28 02:28:39 26 4
gpt4 key购买 nike

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

最佳答案

存储创建的元素:

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

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

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

b.parentNode.removeChild(b)

关于javascript - 使用纯 js 从 html 标签中解包选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52304876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com