开发者

Is it possible to retrieve text a user has highlighted using JavaScript, if the text is not inside a form?

开发者_高级运维I would like to retrieve any text a user may have highlighted with the mouse. I would like to be able to do so from within any arbitrary element. Is this possible?


Absolutely!

Check this out.

http://www.java2s.com/Code/JavaScript/HTML/CapturingaTextSelection.htm


Here's a function that works in all major browsers:

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜