2011-01-17 4 views
2

range.expand('word')을 사용하여 단어를 포함하도록 범위를 만들었다 고 가정합니다. 일반적으로 다음 단어를 추가하려면 range.moveEnd('word', 1)으로 작성합니다. 그러나 이것은 Webkit에서 작동하지 않는 것 같습니다. 아마도 그것은 다르게 구현되어야 하는가?Webkit에서는 범위에 다른 단어를 어떻게 추가합니까?

답변

3

IE에서 완전히 구현되는 TextRange에 대해 이야기하고 있습니다. 다른 브라우저에서는 대신 DOM Level 2 Range 객체를 사용합니다. 대부분의 경우 TextRanges보다 훨씬 우수하지만 expand()과 같은 텍스트 기반 메서드는 없습니다. 그러나 최근의 WebKit 브라우저는 expand() 버전을 구현하고 Webkit과 Firefox 4는 모두 비슷한 기능을 제공하는 Selection 개체의 modify() 메서드를 사용합니다.

예 : http://jsfiddle.net/bzU22/1/

<script type="text/javascript"> 
    function expandSelection() { 
     if (window.getSelection && window.getSelection().modify) { 
      var sel = window.getSelection(); 
      sel.modify("extend", "forward", "word"); 
     } else if (document.selection && document.selection.type == "Text") { 
      var range = document.selection.createRange(); 
      range.moveEnd("word", 1); 
      range.select(); 
     } 
     document.getElementById("test").focus(); 
    } 
</script> 

<input type="button" unselectable onclick="expandSelection();" value="Expand"> 
<p contenteditable="true" id="test">Hello, this is some test text. 
    Select a word and then press the 'Expand' button.</p> 
+0

감사합니다 팀. 전에 var range = document.caretRangeFromPoint (x, y)를 사용하고있었습니다. 해당 항목이 있으므로 sel.modify를 사용할 수 있습니까? – tofutim

+0

브라우저에는 다양한 API가 있습니다. 이 질문에 대한 자세한 정보가 있습니다. http://stackoverflow.com/questions/3189812/creating-a-collapsed-range-from-a-pixel-position-in-ff-webkit –

관련 문제