【发布时间】:2013-06-29 04:29:49
【问题描述】:
$(id).focus(); 将光标位置设置为输入框的开头,但我想将其放在文本的末尾、最后一行和最后一个位置。
【问题讨论】:
标签: javascript jquery html focus
$(id).focus(); 将光标位置设置为输入框的开头,但我想将其放在文本的末尾、最后一行和最后一个位置。
【问题讨论】:
标签: javascript jquery html focus
您可以为此使用setSelectionRange
我的代码 -
HTML -
<textarea rows="8" id="txt1" style="width:400px;" >Hello Hello Hello Hello</textarea>
jquery -
var input = $("#txt1");
var len = input.val().length;
input[0].focus();
input[0].setSelectionRange(len, len);
试试 -
【讨论】:
试试这个:
$(document).ready(function(){
$("#search").focus(function(){
if (this.setSelectionRange)
{
var len = $(this).val().length;
this.setSelectionRange(len, len);
}
else
{
$(this).val($(this).val());
}
});
$("#search").focus();
});
因为并非所有浏览器都支持setSelectionRange。所以最好的解决方案是将setSelectionRange与$(this).val($(this).val());结合起来。欲了解更多信息,请查看:Use JavaScript to place cursor at end of text in text input element
【讨论】:
setSelectionRange Ishan Jain 的回答也是解决方案。但并非所有浏览器都支持setSelectionRange。我认为最好的方法是将这个解决方案与setSelectionRange