将选定的文本扩展为整个单词

时间:2011-10-18 14:55:47

标签: javascript firefox webkit

在IE中,我可以这样做:

var rng = document.selection.createRange();
rng.expand("word");
txt = rng.text;

如何在IE之外进行等效操作?

Select whole word with getSelection 建议使用window.getSelection().modify(),但我不想修改选择。

2 个答案:

答案 0 :(得分:1)

我接受了亚历山大的答案,因为它应该跨越元素边界。我不需要这个,所以我实际使用的解决方案如下。

function GetSelectedText()
{
    var t = '';
    if (window.getSelection) // FF4 with one tab open?
    {
        var rng = window.getSelection().getRangeAt(0);
        expandtoword(rng);
        t = rng.toString();
    }
    else if (document.getSelection) // FF4 with multiple tabs open?
    {
        var rng = document.getSelection().getRangeAt(0);
        expandtoword(rng);
        t = rng.toString();
    }
    else if (document.selection) // IE8
    {
        var rng = document.selection.createRange();
        // expand range to enclose any word partially enclosed in it
        rng.expand("word");
        t = rng.text;
    }

    // convert newline chars to spaces, collapse whitespace, and trim non-word chars
    return t.replace(/\r?\n/g, " ").replace(/\s+/g, " ").replace(/^\W+|\W+$/g, '');
}

// expand FF range to enclose any word partially enclosed in it
function expandtoword(range)
{
    if (range.collapsed)
    {
        return;
    }

    while (range.startOffset > 0 && range.toString()[0].match(/\w/))
    {
        range.setStart(range.startContainer, range.startOffset - 1);
    }

    while (range.endOffset < range.endContainer.length && range.toString()[range.toString().length - 1].match(/\w/))
    {
        range.setEnd(range.endContainer, range.endOffset + 1);
    }
}

答案 1 :(得分:0)

要恢复您的选择,请执行以下操作:

var range = selection.getRangeAt(0); // check for rangeCount in advance
var oldRange = document.createRange();
oldRange.setStart(range.startContainer, range.startOffset);
oldRange.setEnd(range.endContainer, range.endOffset);
...modify the selection and do whatever you need...
selection.removeAllRanges();
selection.addRange(oldRange);