我认为这将是一件非常简单的事情,但我无法让它发挥作用。我正在使用以下代码,但没有成功。我知道这在 ie 中不起作用,我正在使用 chrome。这是 jsFiddle展示。谢谢
$('#ta').focus(function(){
this.selectionStart = this.value.length;
});
最佳答案
这是一个跨浏览器且兼容 jQuery 的解决方案(它支持给定选择器中的多个元素)。
在 Chrome 40x、IE 11 和 FireFox 34x 中测试
$("textarea").focus(function () {
for (var i = 0; i < $(this).length; i++) {
var el = $(this)[i]
window.setTimeout(function () {
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', el.value.length);
range.select();
}
else {
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(el.value.length, el.value.length);
}
else {
el.focus();
}
}
}
}, 1)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="ta">focus on me</textarea><br />
<textarea id="ta2">focus on me</textarea>
关于javascript - 将插入符号移动到焦点文本区域的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28202914/