开发者

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

开发者 https://www.devze.com 2023-03-16 19:23 出处:网络
开发者_高级运维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!

开发者_高级运维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

精彩评论

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