如何在window.getSelection中选择多个单词

时间:2011-09-24 22:33:02

标签: javascript getselection

如何在window.getSelection中选择多个单词。

在此代码中,如果我选择tweenen paragrap,它将锁定单词paragraphs并错过`之间。我需要选择两个单词。

甚至我选择3个字dd 2 spa,它会选择3个字add 2 spaces。感谢。

<script type="text/javascript">
    function Selected() {
        var sel;
        if ((window.getSelection) && (sel = window.getSelection()).modify) {
            sel = window.getSelection();
            if (!sel.isCollapsed) {
                sel.modify("move", "backward", "word");
                sel.modify("extend", "forward", "word");
            }
        }
    }
</script>
<p>put returns between paragraphs, for linebreak add 2 spaces at end</p>
<input type="button" onclick="Selected();" value="selected">

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望按钮将所选内容复制到整个单词。如果是这样,你可以这样做:

现场演示:http://jsfiddle.net/uCHVQ/1/

代码:

function Selected() {
    var sel;
    if ((window.getSelection) && (sel = window.getSelection()).modify) {
        sel = window.getSelection();
        if (!sel.isCollapsed) {

            // Detect if selection is backwards
            var range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);
            var backwards = range.collapsed;
            range.detach();

            // modify() works on the focus of the selection
            var endNode = sel.focusNode, endOffset = sel.focusOffset;
            sel.collapse(sel.anchorNode, sel.anchorOffset);
            if (backwards) {
                sel.modify("move", "forward", "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", "backward", "word");

            } else {
                sel.modify("move", "backward", "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", "forward", "word");
            }
        }
    }
}

(顺便说一句,这段代码最初来自我发布的内容吗?它看起来很熟悉,但我找不到它。)