2010-05-05 3 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 만들기 위해 추가 태그를 넣어 것입니다. 나는 javascript가 추가로 검증하지 않고 선택한 정확한 HTML을 원한다.

이 작업을 수행 할 수있는 방법이 있습니까? 나는 그것을 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> 

작업을 수행하려면 선택 항목의 각 단락마다 각 텍스트의 태그를 사용하여 이와 같은 코드가 필요합니다.

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")); 
} 
:
<p>notselected <span>selected</span></p><p><span>selected</span> notselected</p> 

선택한 모든 노드를 반복하고 같은 선택한 텍스트를 포장해야이 작업을 수행하려면
관련 문제