2012-05-15 2 views
4

이 질문은 유사한 질문 asked here에 태그를 적용하여 선택한 텍스트에 적용하는 방법에 대해 설명합니다. 질문에 대한 답변은되었지만 그 대답은 하나의 큰 결점이있었습니다. 즉, 선택한 동일한 텍스트가 문서의 다른 곳에있는 경우 <span>은 해당 텍스트가 아니라 복제본을 둘러 쌉니다.jQuery - 랩 <span> 선택한 텍스트 주위 - 중복 인스턴스 버그

나는 이것이 아마도 stackoverflow 프로토콜에 반대 할 수 있다는 것을 알고 있지만, 진행 방법에 대한 실제 단서가없이 게시하고 있습니다. 내 가장 좋은 추측은 어떻게 든 선택한 텍스트 (무언가 along these lines) 전에 문자열 길이를 찾을 수 있지만 대체 기능 자체에 통합하는 방법 ... 잘 나는 밀어 사용할 수 있습니다. 누군가?

(내가 mathias-bynens로 이전 게시물에 대한 해결책을 (붙여 넣은) 아래.)

$("p").live("mouseup",function() { 
    selection = getSelectedText(); 
    if(selection.length >= 3) { 
     var spn = '<span class="selected">' + selection + '</span>'; 
     $(this).text($(this).html().replace(selection, spn)); 

    } 
}); 

//Grab selected text 
function getSelectedText(){ 
    if(window.getSelection){ 
     return window.getSelection().toString(); 
    } 
    else if(document.getSelection){ 
     return document.getSelection(); 
    } 
    else if(document.selection){ 
     return document.selection.createRange().text; 
    } 
} 

답변

4

무엇 내가 원하고 링크를 제거 : 당신이 이런 식으로 해킹 안전해야하므로 모든 주요 브라우저에서

$("p").live("mouseup",function() { 
    document.execCommand('CreateLink', false, 'uniqueid'); 
    var sel = $('a[href="uniqueid"]'); 
    sel.wrap('<span class="selected" />') 
    sel.contents().unwrap(); 
}); 

document.execCommand가 지원됩니다. 테스트 한 브라우저에서 브라우저 자체가 태그를 열고 닫을 것이므로 한 HTML 태그 중간에서 다른 HTML 태그 중간까지를 선택하는 경우 태그를 올바르게 중첩해야합니다.

+0

에 의해 나는 이것을 좋아한다. 이것이 조금 더 흘러 나오기 전까지는, 이것을 처리하는 좋은 방법 인 것 같습니다. –

0

내가 당신의 키를 반환 대해 getSelection 무엇인지 파악하고 그와 함께 작업하는 것입니다 생각합니다.

파이어 폭스에 내가이 작업을 수행 할 수 있었다 :

$(document.getSelection().anchorNode).wrap('<div style="color:blue">') 

document.selection.createRange() 당신이 선택한 일을 찾을 수있는 비슷한 일이 있어야합니다.

그래서 뭔가 같은 : 나는 비겁하고 선택한 텍스트를 포장 document.execCommand을 사용하고, 요소를 찾아 그것을 포장 href를합니다 (에서 CreateLink의 execCommand의 세 번째 매개 변수)를 사용

$("p").live("mouseup",function() { 
    var $sel = getSelectedElem(); 
    if($.trim($sel.text()).length >= 3) { 
     $sel.warp('<span class="selected">'); 
    } 
}); 

//Grab selected text 
function getSelectedElem(){ 
    if(window.getSelection){ 
     return $(window.getSelection().anchorNode); 
    } 
    else if(document.getSelection){ 
     return $(document.getSelection().anchorNode) 
    } 
    else if(document.selection){ 
     //todo figure out what to return here: 
     return document.selection.createRange().text; 
    } 
    return $([]); 
} 
0

어떨까요?

document.execCommand("insertHTML", false, "<span class='own-class'>"+ document.getSelection()+"</span>"); 

sourceYeppThat'sMe