Có hai phần cho câu hỏi của bạn.
1) Cách tập trung đầu vào khi tải trang?
Bạn chỉ có thể thêm thuộc tính autofocus
vào đầu vào.
<input id="myinputbox" type="text" autofocus>
Tuy nhiên, điều này có thể không được hỗ trợ trong tất cả các trình duyệt, vì vậy chúng tôi có thể sử dụng javascript.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) Cách đặt con trỏ ở cuối văn bản nhập liệu?
Đây là giải pháp không phải jQuery với một số mã được mượn từ 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();
}
Đây là ví dụ về cách tôi thực hiện việc này với 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>
Khối mã đầu tiên đề nghị thực sự pla lấy con trỏ ở cuối giá trị hiện tại, nó hoạt động tốt. Tôi apreciate giúp đỡ của bạn. – Codex73