开发者

In Webkit, how do I add another word to the range?

Suppose I've made my range so that it covers a word, using range.expand('word'). Typically to add开发者_Python百科 the next word, I would write range.moveEnd('word', 1). But this seems not to work in Webkit. Perhaps it should be implemented differently?


You're talking about TextRanges, which are only fully implemented in IE. Other browsers use the DOM Level 2 Range objects instead, which while being vastly superior to TextRanges in most ways have no equivalent of text-based methods such as expand(). However, recent WebKit browsers do implement a version of expand() and both Webkit and Firefox 4 have the modify() method of the Selection object which provides similar functionality.

Example: 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜