复杂选择的范围

复杂选择的范围

问题描述:

我想突出显示用户选择的文本。我不能使用基于JQuery的API进行高亮显示,因为我想要用户特定的亮点。复杂选择的范围

下面是我的代码的样子。

var range = window.getSelection().getRangeAt(0); 
var sel = window.getSelection(); 
range.setStart(sel.anchorNode, sel.anchorOffset); 
range.setEnd(sel.focusNode,sel.focusOffset); 
highlightSpan = document.createElement("span"); 
highlightSpan.setAttribute("style","background-color: yellow; "); 
highlightSpan.appendChild(range.extractContents()); 
range.insertNode(highlightSpan)  

这在普通情况下,但如果我在不同的段落选择一些文本的extractContents API将验证返回的HTML,并把额外的标签,使其有效的HTML。 我想要的确切的HTML没有额外的JavaScript验证。

这有什么办法可以做到吗?

问候, 蒂娜

+0

重复:http://*.com/questions/2584301/getselection-surroundcontents-across-multiple-tags http://*.com/questions/2582831/highlight-the-text-of-the -dom-range-element,http://*.com/questions/1622629/javascript-highlight-selected-range-button – 2010-05-05 09:02:06

这又拿出了几次:

How can I highlight the text of the DOM Range object? Javascript Highlight Selected Range Button

这里是我的答案:

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

function highlight(colour) { 
    var range, sel; 
    if (window.getSelection) { 
     // Non-IE case 
     sel = window.getSelection(); 
     if (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"; 
    } else if (document.selection && document.selection.createRange) { 
     // IE case 
     range = document.selection.createRange(); 
     range.execCommand("BackColor", false, colour); 
    } 
} 
+0

请看下一个问题。 – 2010-05-05 12:11:08