Javascript:如何un-surroundContents范围 [英] Javascript: how to un-surroundContents range
问题描述
此函数使用范围对象返回用户选择并用粗体标记包装。有没有办法让我删除标签?如< b>文本< b>
= 文本
。
我实际上需要一个切换功能,它将选择包裹在标签&如果已经包含标签,请将其解包。类似于当您切换粗体按钮时文本编辑器所做的操作。
This function uses the range object to return user selection and wrap it in bold tags. is there a method that allows me to remove the tags? As in <b>text<b>
= text
.
I actually need a toggle function that wraps the selection in tags & un-wraps it if already contains tags. Similar to what text editors do when you toggle the bold button.
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);
}
}
推荐答案
在你以前的问题中没有提到这个,因为它听起来像是想要一个围绕元素范围的通用方法,但是对于这个特定的应用程序(即加粗/解开文本),并且假设你不介意一点所使用的精确标签中的跨浏览器变化(
对< bold>
而不是< span style =font-weight:bold>
),最好使用 document.execCommand()
,将切换粗体:
I didn't mention this in your previous question about this because it sounded like you wanted a generic means of surrounding a range within an element, but for this particular application (i.e. bolding/unbolding text), and assuming you don't mind a little cross-browser variation in the precise tags used (<strong>
versus <bold>
versus possibly <span style="font-weight: bold">
), you're best off using document.execCommand()
, which will toggle boldness:
function toggleBold() {
document.execCommand("bold", false, null);
}
当所选内容可编辑时,这将在所有浏览器中运行,即使它不能在IE中编辑。如果您需要在其他浏览器中使用不可编辑的内容,则需要暂时使文档可编辑:
This will work in all browsers when the selected content is editable, and even when it's not editable in IE. If you need it to work on non-editable content in other browsers, you'll need to temporarily make the document editable:
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:如何un-surroundContents范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!