Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

bookmarklet - Javascript get selected text from any textinput/textarea on the page

How can get the selected text from a textbox/textarea if I don't know which one active (focused). I am trying to create a small bookmarklet that will correct the selected text in any type of input on a page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the selection, you want selectionStart and selectionEnd.

As for the currently focused element, use document.activeElement.

So as a combination you can use: http://jsfiddle.net/rBPte/1/.

As Tim Down pointed out, you'd need a more complex solution for Internet Explorer version 8 or lower: Caret position in textarea, in characters from the start

function getText(elem) { // only allow input[type=text]/textarea
    if(elem.tagName === "TEXTAREA" ||
       (elem.tagName === "INPUT" && elem.type === "text")) {
        return elem.value.substring(elem.selectionStart,
                                    elem.selectionEnd);
        // or return the return value of Tim Down's selection code here
    }
    return null;
}

setInterval(function() {
    var txt = getText(document.activeElement);
    document.getElementById('div').innerHTML =
        txt === null ? 'no input selected' : txt;
}, 100);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...