如何使用jQuery选择文本

问题描述:

如何通过jQuery选择文本的一部分并进行处理?例如,我的文字为

How can I select a part of the text and process by jQuery? For example, I have a text as

<div id="test">This is an example text here</div>

我用鼠标选择了几个单词(不是整个div),并希望在其中显示这些单词(#test的一部分)

I select few words (not the whole div) with mouse, and want to show these words (part of #test) in

<div id="target"></div>

方法如下.以下内容适用于所有主流浏览器,包括IE 6.

Here's how. The following works in all major browsers, including IE 6.

function getSelectedText() {
    var selectedText = "", sel;
    if (window.getSelection) {
        selectedText = "" + window.getSelection();
    } else if ( (sel = document.selection) && sel.type == "Text") {
        selectedText = sel.createRange().text;
    }
    return selectedText;
}

$('#target').text( getSelectedText() );