如果我不知道哪一个是活动的(聚焦的),如何从文本框/文本区域获取选定的文本。我正在尝试创建一个小书签,将纠正任何类型的输入在一个页面上的选定文本。
发布于 2011-06-20 19:11:04
对于选择,您需要selectionStart
和selectionEnd
。
对于当前关注的元素,使用document.activeElement
。
因此,您可以组合使用:http://jsfiddle.net/rBPte/1/。
正如Tim Down指出的那样,对于Internet Explorer version8或更低版本,您需要一个更复杂的解决方案: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);
https://stackoverflow.com/questions/6416020
复制相似问题