Javascript 在Webkit中,如何向范围中添加另一个单词?

Javascript 在Webkit中,如何向范围中添加另一个单词?,javascript,webkit,range,textrange,Javascript,Webkit,Range,Textrange,假设我使用range.expand('word')设置了范围,使其覆盖一个单词。通常,为了添加下一个单词,我会编写range.moveEnd('word',1)。但这在Webkit中似乎不起作用。也许它应该以不同的方式实现?你说的是TextRanges,它只在IE中完全实现。其他浏览器使用这些对象,而这些对象虽然在大多数方面远远优于TextRanges,但却没有类似于expand()等基于文本的方法。然而,最近的WebKit浏览器确实实现了一个版本的expand(),WebKit和Firefox

假设我使用
range.expand('word')
设置了范围,使其覆盖一个单词。通常,为了添加下一个单词,我会编写
range.moveEnd('word',1)
。但这在Webkit中似乎不起作用。也许它应该以不同的方式实现?

你说的是
TextRange
s,它只在IE中完全实现。其他浏览器使用这些对象,而这些对象虽然在大多数方面远远优于TextRanges,但却没有类似于
expand()
等基于文本的方法。然而,最近的WebKit浏览器确实实现了一个版本的
expand()
,WebKit和Firefox4都有
选择
对象的方法,它提供了类似的功能

例如:


函数选择(){
if(window.getSelection&&window.getSelection().modify){
var sel=window.getSelection();
选择修改(“延伸”、“向前”、“文字”);
}else if(document.selection&&document.selection.type==“Text”){
var range=document.selection.createRange();
范围。移动结束(“单词”,1);
range.select();
}
document.getElementById(“test”).focus();
}
你好,这是一些测试文本。
选择一个单词,然后按“展开”按钮


谢谢你,蒂姆。我以前使用的是var range=document.caretRangeFromPoint(x,y)。有没有一个等价的工具可以让我使用sel.modify?浏览器为此提供了不同的API。此问题有更多信息:
<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>