gpt4 book ai didi

Javascript:如何取消 surroundContents 范围

转载 作者:搜寻专家 更新时间:2023-11-01 04:11:32 25 4
gpt4 key购买 nike

此函数使用范围对象返回用户选择并将其包装在粗体标记中。有没有一种方法可以让我删除标签?如 <b>text<b> = text .


我实际上需要一个切换功能,将选择包装在标签中,如果已经包含标签,则取消包装。类似于切换粗体按钮时文本编辑器的操作。

if "text" then "<b>text</b>"
else "<b>text</b>" then "text"

...

function makeBold() {

//create variable from selection
var selection = window.getSelection();
if (selection.rangeCount) {
var range = selection.getRangeAt(0).cloneRange();
var newNode = document.createElement("b");

//wrap selection in tags
range.surroundContents(newNode);

//return the user selection
selection.removeAllRanges();
selection.addRange(range);
}
}

最佳答案

我在你之前的问题中没有提到这个,因为听起来你想要一种通用的方法来包围一个元素内的范围,但对于这个特定的应用程序(即加粗/取消加粗文本),并假设你不如果不介意使用的精确标签( <strong><bold> 与可能的 <span style="font-weight: bold"> )有一点跨浏览器的差异,您最好使用 document.execCommand() ,这将切换粗体:

function toggleBold() {
document.execCommand("bold", false, null);
}

当所选内容可编辑时,这将适用于所有浏览器,即使它在 IE 中不可编辑。如果您需要它在其他浏览器中处理不可编辑的内容,您需要暂时将文档设置为可编辑:

function toggleBold() {
var range, sel;
if (window.getSelection) {
// Non-IE case
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand("bold", false, null);
document.designMode = "off";
} else if (document.selection && document.selection.createRange &&
document.selection.type != "None") {
// IE case
range = document.selection.createRange();
range.execCommand("bold", false, null);
}
}

关于Javascript:如何取消 surroundContents 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479151/

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