2011-01-17 29 views

回答

3

你說的是TextRange s,它們只在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 –

相關問題