如何在页面加载时将光标聚焦在特定输入框上?
是否可以同时保留初始文本值并将光标放在输入的末尾?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
如何在页面加载时将光标聚焦在特定输入框上?
是否可以同时保留初始文本值并将光标放在输入的末尾?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
你的问题有两个部分.
1) How to focus an input on page load?个
只需将autofocus
属性添加到输入中即可.
<input id="myinputbox" type="text" autofocus>
但是,并不是所有的浏览器都支持这一点,所以我们可以使用javascript.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) How to place cursor at the end of the input text?个
下面是一个非jQuery解决方案,其中包含一些borrow 自another SO answer的代码.
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>