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

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

Thuộc tính autofocus của đối tượng Input FileUpload (<input type="file">) trong HTML DOM trả về hoặc thiết lập việc ô tải tệp có tự động nhận focus khi trang tải xong hay không.

Cú pháp

Lấy giá trị boolean

inputFileUploadObject.autofocus

Thiết lập autofocus

inputFileUploadObject.autofocus = booleanValue

Các giá trị boolean

booleanValueChi tiết
trueÔ tải tệp sẽ được focus tự động khi tải trang.
falseMặc định: ô tải tệp không được focus tự động.

Ví dụ minh họa

Ví dụ dưới đây trang web có ô tải tệp tự động focus, và nút để tắt tính năng này:

<!DOCTYPE html>
<html>
<head>
<title>Input FileUpload 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>FileUpload-autofocus</legend>
    <label for="FileSelect">Tải lên: <input type="file" id="FileSelect" autofocus> </label><br> 
    <input type="button" onclick="xoaAutofocus()" value="Tắt Autofocus"> 
    <div id="divDisplay"></div> 
  </fieldset> 
</form> 
<script> 
  var divDisplay = document.getElementById("divDisplay"); 
  var inputFile = document.getElementById("FileSelect"); 
  divDisplay.textContent = 'Tự động focus: ' + inputFile.autofocus; 
  function xoaAutofocus() { 
    inputFile.autofocus = false; 
    divDisplay.textContent = 'Tự động focus: ' + inputFile.autofocus; 
  } 
</script> 
</body> 
</html>

Kết quả

  • Khi tải trang: ô chọn file được focus ngay (có viền nổi bật).
  • Nhấn Tắt Autofocus: giá trị hiển thị chuyển thành false.

Lưu ý: Chỉ có một phần tử được phép có autofocus trên một trang. Nếu nhiều phần tử có, trình duyệt sẽ ưu tiên phần tử đầu tiên trong DOM.