开发者

Storing Highlighted text in a variable

开发者 https://www.devze.com 2023-01-08 11:31 出处:网络
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.selection.createRange().text

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.selection.createRange().text but this hasn't been working. Are there any possible alternatives? Here's the code:

function moremagic(){
var output = document.selection.createRan开发者_如何转开发ge();
alert("I Work!");}

When I run the function, it doesn't make it to the write statement so I know something is wrong.


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.


Yep, you want window.getSelection.


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

精彩评论

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