Javascript 获取文本框中选定的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2377875/
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
Get selected text in a textbox
提问by Ant
How can I get the character positions of the selected text in an HTML <input>textbox element? window.getSelection()doesn't work inside textboxes.
如何在 HTML<input>文本框元素中获取所选文本的字符位置?window.getSelection()在文本框内不起作用。
回答by Ulf Lindback
回答by Sarfraz
........
…………
<script language=javascript>
function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
document.aform.selectedtext.value = txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()">
<form name=aform >
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
Reference: http://www.codetoad.com/javascript_get_selected_text.asp
参考:http: //www.codetoad.com/javascript_get_selected_text.asp
回答by Ry-
In case you don't need to support really old versions of Internet Explorer, just use the element's selectionEndand selectionStartproperties.
如果您不需要支持真正旧版本的 Internet Explorer,只需使用元素的selectionEnd和selectionStart属性。

