如何突出显示DOM Range对象的文本?

gan*_*ati 15 javascript dom range highlight

我使用鼠标在html页面(在firefox中打开)选择一些文本,并使用javascript函数,我创建/获取与所选文本对应的rangeobject.

 userSelection =window.getSelection(); 
 var rangeObject = getRangeObject(userSelection);
Run Code Online (Sandbox Code Playgroud)

现在我想突出显示rangeobject下的所有文本.我这样做,

  var span = document.createElement("span");
  rangeObject.surroundContents(span);
  span.style.backgroundColor = "yellow";
Run Code Online (Sandbox Code Playgroud)

好吧,这个工作正常,只有当rangeobject(起始点和端点)位于同一个textnode中时,它才会突出显示相应的text.Ex

    <p>In this case,the text selected will be highlighted properly,
       because the selected text lies under a single textnode</p>
Run Code Online (Sandbox Code Playgroud)

但是如果rangeobject覆盖了多个textnode,那么它就不能正常工作,它只突出显示位于第一个textnode中的文本,Ex

 <p><h3>In this case</h3>, only the text inside the header(h3) 
  will be highlighted, not any text outside the header</p> 
Run Code Online (Sandbox Code Playgroud)

任何想法我怎么做,所有在rangeobject下的文本,突出显示,独立于范围是在单个节点还是多个节点?谢谢....

Tim*_*own 25

我建议使用document's或TextRange's execCommand方法,它是为了这个目的而构建的,但通常用于可编辑的文档中.以下是我对类似问题的回答:

以下应该做你想要的.在非IE浏览器中,它打开designMode,应用背景颜色,然后再次关闭designMode.

UPDATE

修复了在IE 9中工作.

更新2013年9月12日

这是一个链接,详细说明了删除此方法创建的高亮显示的方法:

/sf/answers/567439841/

function makeEditableAndHighlight(colour) {
    var range, 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;
    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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ker 6

Rangy是一个跨浏览器的范围和选择库,它的CSS Class Applier 模块完美地解决了这个问题。我正在使用它来在一系列桌面浏览器和 iPad 上实现突出显示,并且效果很好。

Tim Down 的回答很棒,但 Rangy 使您不必自己编写和维护所有功能检测代码。

  • 我刚刚注意到 [Tim Down 是 Rangy 的作者](http://code.google.com/u/107383371366938520460/)。:) (10认同)