2011-09-11 3 views
6

getSelection 함수를 사용하여 기사에서보기 상자까지 단어를 선택하고 싶습니다.getSelection을 사용하여 전체 단어 선택

여기 내 코드는 http://jsfiddle.net/xQKNh/2/입니다.

이제 전체 단어를 선택하기 위해 JavaScript를 사용하는 방법에 대해 물어보고 싶습니다. 내가 r question about pro을 선택하면 내 코드에 대한 설명은

,

Is your question about programming? 

,의 view box

r question about pro 

하지만 어떻게 단어가 완료 만드는 방법을 보여줍니다? 이 출력되도록 :

your question about programming. 

자바 스크립트 코드 :

function getSelected() { 
    if(window.getSelection) { return window.getSelection(); } 
    else if(document.getSelection) { return document.getSelection(); } 
    else { 
    var selection = document.selection && document.selection.createRange(); 
    if(selection.text) { return selection.text; } 
    return false; 
    } 
    return false; 
} 
$(document).ready(function() { 
    $('#content-area').mouseup(function() { 
    var selection = getSelected(); 
    if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) { 
     $('#show-text').html(selection) 
    } 
    }); 
}); 

답변

16

최근 버전의 Firefox 및 WebKit 브라우저에는 Selection 객체의 modify() (work-in-progress spec 참조) 메소드가 내장되어 있습니다. IE는 버전 4 이후 완전히 다른 방법을 사용했습니다. 두 경우 모두이 방법은 요소 경계를 넘어 작업 할 때 상당한 이점이 있습니다.

다음 예는 지난 2 년 동안 출시 된 IE 4 이상, Firefox 4 이상, Safari 및 Chrome에서 작동합니다. Opera는 아직까지 Selection 객체의 modify() 메소드를 지원하지 않습니다.

UPDATE 20 년 10 월 2011

나는 (이 코멘트에서 지적했듯이, 이전에 비 IE 브라우저에서 제대로 작동하지 않았다) 이제 실제로는 (대부분)이 일을 다시 작성했습니다. 불행히도 IE가 아닌 곳에서는 선택 확장이 너무 욕심 거리며 전체 단어가 이미 선택되어 있으면 다음 단어로 선택 항목을 확장하지만 지금은 쉽게 찾을 수 없습니다.

UPDATE는 2012년 6월 11일

지금 this answer to a related question의 개선과 함께이 업데이트되었습니다. Matt M과 Fong-Wan Chau에게 감사드립니다.

라이브 데모 : http://jsfiddle.net/rrvw4/23/

코드 :

function snapSelectionToWord() { 
    var sel; 

    // Check for existence of window.getSelection() and that it has a 
    // modify() method. IE 9 has both selection APIs but no modify() method. 
    if (window.getSelection && (sel = window.getSelection()).modify) { 
     sel = window.getSelection(); 
     if (!sel.isCollapsed) { 

      // Detect if selection is backwards 
      var range = document.createRange(); 
      range.setStart(sel.anchorNode, sel.anchorOffset); 
      range.setEnd(sel.focusNode, sel.focusOffset); 
      var backwards = range.collapsed; 
      range.detach(); 

      // modify() works on the focus of the selection 
      var endNode = sel.focusNode, endOffset = sel.focusOffset; 
      sel.collapse(sel.anchorNode, sel.anchorOffset); 

      var direction = []; 
      if (backwards) { 
       direction = ['backward', 'forward']; 
      } else { 
       direction = ['forward', 'backward']; 
      } 

      sel.modify("move", direction[0], "character"); 
      sel.modify("move", direction[1], "word"); 
      sel.extend(endNode, endOffset); 
      sel.modify("extend", direction[1], "character"); 
      sel.modify("extend", direction[0], "word"); 
     } 
    } else if ((sel = document.selection) && sel.type != "Control") { 
     var textRange = sel.createRange(); 
     if (textRange.text) { 
      textRange.expand("word"); 
      // Move the end back to not include the word's trailing space(s), 
      // if necessary 
      while (/\s$/.test(textRange.text)) { 
       textRange.moveEnd("character", -1); 
      } 
      textRange.select(); 
     } 
    } 
} 
+1

안으로 chiming을 주셔서 감사합니다.이것은 더 나은 대답처럼 보입니다. –

+0

@James : 이전의 IE에 대한 'TextRange' 기반의 레인지 만의 대답은 제 대답보다 더 많은 브라우저를 다룰 것입니다. 그래서 OP의 요구 사항에 따라 당신의 것이 더 좋을 수도 있습니다. –

+0

두 분은 훌륭한 분입니다. 두 분 덕분에 나는 tim으로 표를 바꾼다.하지만 제임스에게도 감사한다. –

5

여기에 트릭 DOM ranges를 사용하는 것입니다. 그런 다음 공간을 공격 할 때까지 범위를 어느 방향으로 확장 할 수 있습니다. 그래서 (광범위하게 테스트되지 않은 경고) :

function getSelected() { 
    if(window.getSelection) { return window.getSelection(); } 
    else if(document.getSelection) { return document.getSelection(); } 
    else { 
    var selection = document.selection && document.selection.createRange(); 
    if(selection.text) { return selection.text; } 
    return false; 
    } 
    return false; 
} 

function expand(range) { 
    if (range.collapsed) { 
     return; 
    } 

    while (range.toString()[0].match(/\w/)) { 
     range.setStart(range.startContainer, range.startOffset - 1); 
    } 

    while (range.toString()[range.toString().length - 1].match(/\w/)) { 
     range.setEnd(range.endContainer, range.endOffset + 1); 
    } 
} 

$(document).ready(function() { 
    $('#content-area').mouseup(function() { 
    var selectionRange = getSelected().getRangeAt(0); 
    var start = selectionRange.startOffset; 
    expand(selectionRange); 
    var selection = selectionRange.toString(); 
    if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) { 
     $('#show-text').html(selection) 
    } 
    }); 
}); 

최적화는 독자의 연습 문제로 남겨 두었습니다.

+0

훌륭한 일, 덕분에 나에게 하나의 교훈을 제공합니다. –

+0

감사합니다. 흥미로운 문제였습니다. –

+1

단어의 일부가 다른 요소에 포함되어 있으면이 기능이 작동하지 않습니다. IE 9에서는'window.getSelection()'이나'Range'를 지원하지 않습니다. –

관련 문제