2010-05-05 39 views
5

我想在選定的文本週圍插入我自己的自定義標籤和腳本。這樣在用戶選擇上插入自定義標籤

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("abbr"); 
highlightSpan.setAttribute("style","background-color: yellow;"); 
highlightSpan.setAttribute("onmouseout","javascript:HideContentFade(\"deleteHighlight\");"); 
highlightSpan.setAttribute("onmouseover","javascript:ShowHighlighter(\"deleteHighlight\",\""+id_val+"\");"); 
highlightSpan.appendChild(range.extractContents()); 
range.insertNode(highlightSpan); 

某事,這工作在正常情況下,但如果我在不同的段落選擇一些文本的extractContents API將驗證返回的HTML,並把額外的標籤,使其有效的HTML。我想要的是確切的HTML,沒有額外的JavaScript驗證。

這有什麼辦法可以做到嗎? 我已經嘗試過How can I highlight the text of the DOM Range object?中提到的方式,但事情是我想要用戶特定的亮點,所以如果A添加了一些亮點B應該無法看到它。爲此我準備好了我的後端代碼。

回答

0

如果您使用標記包裝屬於不同段落的選定文本,則會創建無效的HTML代碼。

這是您將生成的無效HTML代碼示例。

<p>notselected <span>selected</p><p>selected</span> notselected</p> 

爲了完成你的任務,你需要使用標籤產生這樣的代碼選擇的每個段落每個文本換行。

<p>notselected <span>selected</span></p><p><span>selected</span> notselected</p> 

要做到這一點,你必須遍歷選定的所有節點,敷選定的文本是這樣的:

function wrapSelection() { 
    var range, start, end, nodes, children; 

    range = window.getSelection().getRangeAt(0); 
    start = range.startContainer; 
    end = range.endContainer; 

    children = function (parent) { 
     var child, nodes; 

     nodes = []; 
     child = parent.firstChild; 

     while (child) { 
      nodes.push(child); 
      nodes = nodes.concat(children(child)); 
      child = child.nextSibling; 
     } 

     return nodes; 
    } 

    nodes = children(range.commonAncestorContainer); 
    nodes = nodes.filter(function (node) { 
     return node.nodeType === Node.TEXT_NODE; 
    }); 
    nodes = nodes.slice(nodes.indexOf(start) + 1, nodes.indexOf(end)); 
    nodes.forEach(function (node) { 
     wrap = window.document.createElement("span"); 
     node.parentNode.insertBefore(wrap, node); 
     wrap.appendChild(node); 
    }); 

    start = new Range(); 
    start.setStart(range.startContainer, range.startOffset); 
    start.setEnd(range.startContainer, range.startContainer.length); 
    start.surroundContents(window.document.createElement("span")); 

    end = new Range(); 
    end.setStart(range.endContainer, 0); 
    end.setEnd(range.endContainer, range.endOffset); 
    end.surroundContents(window.document.createElement("span")); 
} 
相關問題