2010-04-06 62 views
9

我有一个脚本,可以改变已选择文本的背景颜色。但是,当我在跨多个元素/标签选择文本时遇到问题。getSelection&surroundContent跨多个标签

,我已经得到的代码是:

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初学者。

有没有其他方法可以复制我想要实现的功能?

非常感谢。

+0

重复http://stackoverflow.com/questions/2582831/highlight-the-text-of-the-dom-range-element和http://stackoverflow.com/questions/1622629/javascript-highlight-selected -range-button – 2010-04-06 11:18:05

回答

12

这个问题今天已经被问:How can I highlight the text of the DOM Range object?

这里是我的答案:

以下应该做你想要什么。在非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); 
    } 
} 
+1

非常感谢蒂姆,工作完美,并为重复道歉。另一个线程没有出现在我的搜索中。 – lethalbody 2010-04-06 14:34:06

+1

但你怎么称呼功能*高亮*? – yalematta 2015-09-02 20:19:29

+0

@LayaleMatta:例子:'highlight(“#ff0000”)'会为当前选中的文本添加一个红色背景。 – 2015-09-03 20:58:18

2

嗯,我觉得用mark.js库在这种情况下,是伟大的工作。该库的目的是突出显示HTML文档中某个单词的所有实例,但可以通过过滤器选项功能对其进行调整,并且可以通过每个选项功能添加其他范围属性。

检查这个JSFiddle sample已完成的代码,突出用户的选择,甚至可以跨多个HTML元素。