如何在 JavaScript 中获取 textarea 选定文本的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12194113/
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
How to get range of selected text of textarea in JavaScript
提问by user1619672
I am trying to retrieve/find the start point and end point of selection in textarea. Here is my code which work fine in Mozilla and chrome but not working in IE9
我正在尝试在 textarea 中检索/查找选择的起点和终点。这是我的代码,它在 Mozilla 和 chrome 中运行良好,但在 IE9 中不起作用
<script type="txt/javascript">
function update(o) {
var t = o.value, s = getSelectionStart(o), e = getSelectionEnd(o);
alert("start :" + s + " End :" + e);
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
rse = r.text.length;
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
function getSelectionEnd(o) {
if (o.createTextRange) {
var r = document.selection.createRang;e().duplicate()
r.moveStart('character', -o.value.length)
return r.text.length
} else return o.selectionEnd
}
</script>
<textarea id ="text" rows=10 cols="50" onselect="update(this);"></textarea>
When I test this code in Mozilla and chrome it gives me correct answer but when I run this code on IE9 It shows -1 for start and any value for end .
当我在 Mozilla 和 chrome 中测试这段代码时,它给了我正确的答案,但是当我在 IE9 上运行这段代码时,它显示 -1 表示开始,任何值表示结束。
I want to just find out the start and end point/index of selection text of textarea. Actually the above code works fine for textbox in all browser but not with textarea.
我只想找出textarea的选择文本的起点和终点/索引。实际上,上面的代码适用于所有浏览器中的文本框,但不适用于 textarea。
Please suggest me ...
请给我建议...
采纳答案by tsergium
Use the code below or check this fiddle
使用下面的代码或检查这个小提琴
function getTextSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
alert("start :" + start + " End :" + end);
}
回答by Toastrackenigma
While the original answer may have helped the OP in 2012, things have changed, and this has now become simpler, at least in modern browsers.
虽然最初的答案可能在 2012 年对 OP 有所帮助,但事情已经发生了变化,现在变得更简单,至少在现代浏览器中是这样。
You can use the Javascript selectionStart
and selectionEnd
attributes of the textarea.
您可以使用文本区域的 JavascriptselectionStart
和selectionEnd
属性。
Basic Usage:
基本用法:
These are both standard attributes that will work in today's major browsers (Chrome, Safari, Firefox, Opera, Edge, IE).
这些都是适用于当今主要浏览器(Chrome、Safari、Firefox、Opera、Edge、IE)的标准属性。
For example:
例如:
console.log(document.getElementById("text").selectionStart,document.getElementById("text").selectionEnd)
will return both the start and end point of the selection in the textarea with the ID text
.
将返回文本区域中 ID 为所选内容的起点和终点text
。
Boundary Cases:
边界情况:
If there is no item selected in the textarea, then both the start and end attributes will return the last position of the caret. If the textarea has not recieved focus yet, the attributes will both return a value of 0
.
如果 textarea 中没有选中的项目,则 start 和 end 属性都将返回插入符号的最后位置。如果 textarea 尚未收到焦点,则属性都将返回 值0
。
Changing the Selection:
更改选择:
By setting these attributes to new values, you will adjust the active text selection. Thus, you can also use this to select text in a textarea.
通过将这些属性设置为新值,您将调整活动文本选择。因此,您也可以使用它来选择文本区域中的文本。
Checking if a Selection is in Place:
检查选择是否到位:
You can check if there is currently a selection by checking if the values are both different, i.e. if
您可以通过检查值是否不同来检查当前是否有选择,即
document.getElementById("text").selectionStart != document.getElementById("text").selectionEnd
is true, then there is a text selection.
为真,则有文字选择。