getSelection& surroundContents跨多个标签 [英] getSelection & surroundContents across multiple tags
问题描述
我有一个脚本可以更改已选择的文本的背景颜色。但是,当跨多个元素/标签选择文本时,我遇到了问题。
I've got a script that changes the background colour of text that has been selected. However i'm encountering an issue when the text is selected across multiple elements/tags.
我得到的代码是:
var text = window.getSelection().getRangeAt(0);
var colour = document.createElement("hlight");
colour.style.backgroundColor = "Yellow";
text.surroundContents(colour);
输出的错误是:
Error: The boundary-points of a range does not meet specific requirements. =
NS_ERROR_DOM_RANGE_BAD_BOUNDARYPOINTS_ERR
Line: 7
我认为这与getRange()函数虽然我不太清楚如何继续,因为我是javascript的初学者。
I believe this is to do with the getRange() function though i'm not too sure how to proceed since I am a beginner at javascript.
还有其他方法我可以复制我想要的东西实现?
Is there any other way I can replicate what I am trying to achieve?
非常感谢。
推荐答案
今天有人提出这个问题:如何突出显示DOM Range对象的文本?
This question has been asked today: How can I highlight the text of the DOM Range object?
这是我的回答:
以下内容可以满足您的需求。在非IE浏览器中,它打开designMode,应用背景颜色,然后再次关闭designMode。
The following should do what you want. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.
更新
已修复在IE 9中工作。
Fixed to work in IE 9.
function makeEditableAndHighlight(colour) {
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
这篇关于getSelection& surroundContents跨多个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!