![](/img/trans.png)
[英]SurroundContents on a range spanning multiple tags (getRangeAt problem?)
[英]getSelection & surroundContents across multiple 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的初學者。
有沒有其他方法可以復制我想要實現的目標?
非常感謝。
今天有人問過這個問題: 如何突出顯示DOM Range對象的文本?
這是我的答案:
以下應該做你想要的。 在非IE瀏覽器中,它打開designMode,應用背景顏色,然后再次關閉designMode。
UPDATE
修復了在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);
}
}
我認為在這種情況下使用mark.js庫非常棒。 該庫的目的是突出顯示HTML文檔中某個單詞的所有實例,但可以通過過濾器選項功能進行調整,並且可以通過每個選項功能添加其他跨度屬性。
function markFunc(node, text, color) {
var instance = new Mark(node);
instance.mark(text, {
"element": "span",
"className": color,
"acrossElements": true,
"separateWordSearch": false,
"accuracy": "partially",
"diacritics": true,
"ignoreJoiners": true,
"each": function(element) {
element.setAttribute("id", "sohayb");
element.setAttribute("title", "sohayb_title");
},
"done":function(totalMarks) {
window.getSelection().empty();//This only in Chrome
console.log("total marks: " + totalMarks);
},
"filter": function(node, term, totalCounter, counter) {
var res = false;
if (counter == 0) {
res = selectionRange.isPointInRange(node, selectionRange.startOffset);
} else {
res = selectionRange.isPointInRange(node, 1);
}
console.log("Counter: " + counter + ", startOffset: " + selectionRange.startOffset);
return res;
}
});
};
檢查此JSFiddle示例以查找突出顯示用戶選擇的已完成代碼,甚至可以跨多個HTML元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.