Storing Highlighted text in a variable

前端 未结 3 1338
栀梦
栀梦 2021-01-16 11:35

Is there a javascript function that will allow me to capture the text that is currently highlighted with the cursor and store it in a variable? I\'ve been trying document.se

相关标签:
3条回答
  • 2021-01-16 11:59

    Ungraciously stolen from another question:

    function getSelectedText() {
        if (window.getSelection) {
            return window.getSelection();
        }
        else if (document.selection) {
            return document.selection.createRange().text;
        }
        return '';
    }
    

    Use this in a "onClick" function or whatever and it will return the selected text in almost any browser.

    0 讨论(0)
  • 2021-01-16 11:59
    function getSelectedText() {
        if (window.getSelection) {
            return "" + window.getSelection();
        } else if (document.selection && document.selection.type == "Text") {
            return document.selection.createRange().text;
        }
        return "";
    }
    
    0 讨论(0)
  • 2021-01-16 12:03

    Yep, you want window.getSelection.

    0 讨论(0)
提交回复
热议问题