javascript Javascript从页面上的任何文本输入/文本区域获取选定的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6416020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript get selected text from any textinput/textarea on the page
提问by Baruch
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.
如果我不知道哪个是活动的(重点),如何从文本框/文本区域中获取选定的文本。我正在尝试创建一个小书签,它将更正页面上任何类型输入中的选定文本。
回答by pimvdb
For the selection, you want selectionStart
and selectionEnd
.
对于选择,您需要selectionStart
和selectionEnd
。
As for the currently focused element, use document.activeElement
.
对于当前聚焦的元素,使用document.activeElement
.
So as a combination you can use: http://jsfiddle.net/rBPte/1/.
因此,您可以组合使用: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
正如 Tim Down 所指出的,对于 Internet Explorer 8 或更低版本,您需要一个更复杂的解决方案:文本区域中的插入符号位置,从一开始就以字符为单位
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);