2011-01-17 34 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 –

相关问题