Javascript:将插入符号移动到最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4715762/
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: Move caret to last character
提问by Adam
I have a textarea and when I click in it I want to move the caret to the last character so Something[caret]
我有一个 textarea,当我点击它时,我想将插入符号移动到最后一个字符 Something[caret]
function moveCaret(){
// Move caret to the last character
}
<textarea onclick="moveCaret();">
Something
</textarea>
As I know this is somehow possible with the TextRange object, but I don't really know how to use it
据我所知,这在 TextRange 对象中是可行的,但我真的不知道如何使用它
EDIT:I would love to see only pure javascript solutions so no libraries please.
编辑:我希望只看到纯 javascript 解决方案,所以请不要使用库。
回答by Tim Down
The following function will work in all major browsers, for both textareas and text inputs:
以下函数适用于所有主要浏览器,用于文本区域和文本输入:
function moveCaretToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
However, you really shouldn't do this whenever the user clicks on the textarea, since the user will not be able to move the caret with the mouse. Instead, do it when the textarea receives focus. There is also a problem in Chrome, which can be worked around as follows:
但是,您真的不应该在用户单击 textarea 时执行此操作,因为用户将无法使用鼠标移动插入符号。相反,当 textarea 获得焦点时执行。Chrome 中也存在一个问题,可以按如下方式解决:
Full example: http://www.jsfiddle.net/ghAB9/3/
完整示例:http: //www.jsfiddle.net/ghAB9/3/
HTML:
HTML:
<textarea id="test">Something</textarea>
Script:
脚本:
var textarea = document.getElementById("test");
textarea.onfocus = function() {
moveCaretToEnd(textarea);
// Work around Chrome's little problem
window.setTimeout(function() {
moveCaretToEnd(textarea);
}, 1);
};

