Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính autofocus của Input Number trong HTML DOM

Thuộc tính autofocus của <input type="number"> cho phép trả về hoặc thiết lập việc input số có tự động nhận focus khi trang tải xong hay không.

Cú pháp

Lấy giá trị:

numberInput.autofocus

Thiết lập giá trị:

numberInput.autofocus = true | false

Ví dụ: Tắt autofocus bằng nút bấm

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM autofocus property</title>
    <style>
        body { text-align: center; background: #1b203a; color: #ff8741; font-family: sans-serif; padding: 20px; }
        p { font-size: 1.2rem; }
        input[type="number"] {
            border: none; background: #ffffff4a; height: 1.2rem;
            padding: 8px; color: white; font-weight: bold; font-size: 1rem;
        }
        button {
            background-color: #dc3545; color: white; padding: 8px 16px;
            border: none; width: 120px; margin: 10px; border-radius: 25px;
            outline: none; cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Ví dụ autofocus Property</h1>
    <p>Nhấn nút Disable để tắt autofocus</p>
    <input type="number" autofocus value="23450004">
    <br><br>
    <button onclick="disableAutofocus()">Tắt autofocus</button>
    <script>
        function disableAutofocus() {
            document.querySelector("input").autofocus = false;
        }
    </script>
</body>
</html>

Kết quả

Khi tải trang, input number tự động focus:

Thuộc tính autofocus của Input Number trong HTML DOM

Nhấn "Tắt autofocus" - lần tải sau không focus:

Thuộc tính autofocus của Input Number trong HTML DOM

ℹ️ Lưu ý: Chỉ một phần tử nên có autofocus trên trang. Thay đổi bằng JS chỉ có hiệu lực khi reload trang.