什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
如果先设置值,再设置焦点,光标将始终出现在最后。
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
这是用来测试的小提琴 https://jsfiddle.net/5on50caf/1/
其他回答
如果输入字段只需要一个静态默认值,我通常用jQuery这样做:
$('#input').focus().val('Default value');
这似乎在所有浏览器中都有效。
简单。在编辑或更改值时,首先放置焦点,然后设置值。
$("#catg_name").focus();
$("#catg_name").val(catg_name);
如果先设置值,再设置焦点,光标将始终出现在最后。
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
这是用来测试的小提琴 https://jsfiddle.net/5on50caf/1/
设置光标时,点击文本区域的文本结束… 这段代码的变体是…也工作!Firefox, IE, Safari, Chrome..
在服务器端代码中:
txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")
在Javascript中:
function sendCursorToEnd(obj) {
var value = $(obj).val(); //store the value of the element
var message = "";
if (value != "") {
message = value + "\n";
};
$(obj).focus().val(message);
$(obj).unbind();
}
现在是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> .