什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
试试这个,它对我很有效:
//input is the input element
input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.
为了让光标移动到最后,输入必须先有焦点,然后当值改变时,它才会移动到最后。如果你将.value设置为相同的值,它在chrome中不会改变。
其他回答
好吧,我只用:
$("#myElement").val($("#myElement").val());
超级简单(你可能需要关注input元素)
inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;
适用于所有浏览器和所有情况:
function moveCursorToEnd(el) {
window.setTimeout(function () {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}, 1);
}
如果您需要从onFocus事件处理程序移动光标,需要超时
<input id="input_1">
<input id="input_2" type="hidden">
<script type="text/javascript">
//save input_1 value to input_2
$("#input_2").val($("#input_1").val());
//empty input_1 and add the saved input_2 into input_1
$("#input_1").val("").val($("#input_2").val()).focus();
</script>
如果先设置值,再设置焦点,光标将始终出现在最后。
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
这是用来测试的小提琴 https://jsfiddle.net/5on50caf/1/