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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…