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

Thuộc tính download của DOM Anchor trong HTML


Giới thiệu

Thuộc tính download của đối tượng Anchor (DOM) đọc hoặc ghi giá trị thuộc tính download của thẻ <a>. Khi có thuộc tính này, trình duyệt sẽ tải file về thay vì điều hướng, và gợi ý tên file là giá trị này (phần mở rộng tự động thêm dựa trên file thực tế).

Cú pháp

// Lấy
anchorObject.download
// Gán
anchorObject.download = "ten_file"

Ví dụ minh họa

<!DOCTYPE html>
<html>
<body>
  <h2>ReactJS</h2>
  <a id="myid" href="https://www.tutorialspoint.com/images/reactjs.png" download="Hoc ReactJS">
    <img src="https://www.tutorialspoint.com/images/reactjs.png" alt="ReactJS" width="200" height="200">
  </a>
  <button onclick="display()">Hiển thị giá trị download</button>
  <p id="demo"></p>
  <script>
    function display() {
      var val = document.getElementById("myid").download;
      document.getElementById("demo").innerHTML = val;
    }
  </script>
</body>
</html>

Kết quả hiển thị

Nhấn nút hiển thị "Hoc ReactJS". Nhấp hình ảnh sẽ tải file reactjs.png với tên gợi ý "Hoc ReactJS.png".