2010-05-05 103 views
0

我想突出顯示用戶選擇的文本。我不能使用基於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://stackoverflow.com/questions/2584301/getselection-surroundcontents-across-multiple-tags http://stackoverflow.com/questions/2582831/highlight-the-text-of-the -dom-range-element,http://stackoverflow.com/questions/1622629/javascript-highlight-selected-range-button – 2010-05-05 09:02:06

回答

0

這又拿出了幾次:

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