getSelection & surroundContents across multiple tags
我有一个脚本,可以更改所选文本的背景颜色。 但是,当跨多个元素/标签选择文本时,我遇到了一个问题。
我得到的代码是:
1 2 3 4 | var text = window.getSelection().getRangeAt(0); var colour = document.createElement("hlight"); colour.style.backgroundColor ="Yellow"; text.surroundContents(colour); |
输出的错误是:
1 2 3 | 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。
更新
修复了在IE 9中的工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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文档中某个单词的所有实例,但是可以通过filter选项功能对其进行调整,并可以通过each选项功能添加其他span属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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元素也是如此。