2011-01-17 6 views

答えて

3

あなたはTextRangeについて話していますが、これはIEでのみ完全に実装されています。他のブラウザでは代わりに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 –

関連する問題