你的问题有两个部分。
1)如何将输入集中在页面加载上?
您只需添加autofocus
属性到输入。
<input id="myinputbox" type="text" autofocus>
然而,这可能不是所有浏览器都支持,所以我们可以使用 javascript。
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2)如何将光标置于输入文本的末尾?
这是一个非 jQuery 解决方案,其中包含一些借用的代码另一个SO答案 https://stackoverflow.com/a/1675345/5651.
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
下面是我如何使用 jQuery 实现此目的的示例。
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>