什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
其他回答
input = $('input');
input.focus().val(input.val()+'.');
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}
好吧,我只用:
$("#myElement").val($("#myElement").val());
在jQuery中,这是
$(document).ready(function () {
$('input').focus(function () {
$(this).attr('value',$(this).attr('value'));
}
}
我刚在iOS中发现,设置textarea。textContent属性每次都会将光标放在textarea元素中文本的末尾。这种行为是我的应用程序中的一个bug,但似乎是你可以故意使用的东西。
现在是2019年,上面的方法对我来说都没用,但这个方法管用,摘自https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/
函数moveCursorToEnd(id) var el = document.getElementById(id) el.focus () If(类型的el。selectionStart == "number") { 埃尔。selectionStart = el。selectionEnd = el.value.length; } else if(类型的el。createTextRange != "undefined") { var range = el.createTextRange(); range.collapse(假); range.select (); } } <input id="myinput" type="text" /> <a href="#" onclick="moveCursorToEnd('myinput')>移动光标到结束</a> .