Thuộc tính autofocus của đối tượng Input URL trong HTML DOM xác định ô nhập URL có tự động nhận focus khi trang tải xong hay không. Chỉ một phần tử trên trang được autofocus.
Cú pháp
Lấy giá trị boolean
inputURLObject.autofocus
Thiết lập autofocus
inputURLObject.autofocus = booleanValue
Các giá trị boolean
| booleanValue | Chi tiết |
|---|---|
| True | Ô URL tự động focus khi tải trang. |
| False | Mặc định: không tự động focus. |
Ví dụ minh họa
Ô URL có placeholder và autofocus. Nhấn nút tắt autofocus (hiệu lực load sau):
<!DOCTYPE html>
<html>
<head>
<title>Input URL autofocus</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; }
input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>URL-autofocus</legend>
<label for="URLSelect">URL: <input type="url" id="URLSelect" placeholder="https://www.google.com" autofocus> </label>
<input type="button" onclick="xoaAutofocus()" value="Tắt Autofocus">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var inputURL = document.getElementById("URLSelect");
divDisplay.textContent = 'Autofocus: ' + inputURL.autofocus;
function xoaAutofocus() {
inputURL.autofocus = false;
divDisplay.textContent = 'Autofocus: ' + inputURL.autofocus;
}
</script>
</body>
</html>
Kết quả
- Tải trang: ô URL tự động focus, sẵn sàng gõ.
- Hiển thị "Autofocus: true".
- Nhấn Tắt Autofocus: "Autofocus: false".
Lưu ý: Để focus ngay lập tức qua JS, dùng inputURL.focus(). Thuộc tính autofocus chỉ tác động khi load trang.