ToggleEvent: source property

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Thuộc tính chỉ đọc source của giao diện ToggleEvent là một phiên bản đối tượng Element biểu diễn phần tử điều khiển popover HTML đã khởi tạo việc chuyển đổi.

Giá trị

Một phiên bản đối tượng Element, hoặc null nếu popover không được kích hoạt bởi một phần tử điều khiển.

Mô tả

Một phần tử <button> có thể được đặt làm điều khiển popover bằng cách chỉ định id của phần tử popover trong thuộc tính commandfor hoặc popovertarget của nó.

Khi sự kiện toggle kích hoạt trên popover, thuộc tính source của đối tượng sự kiện ToggleEvent sẽ chứa tham chiếu đến nút điều khiển popover đã khởi tạo việc chuyển đổi. Điều này hữu ích để chạy mã khác nhau để phản hồi sự kiện toggle tùy thuộc vào điều khiển popover nào đã khởi tạo nó.

Nếu phần tử popover không được kích hoạt bởi một nút điều khiển, ví dụ nếu nó được điều khiển bằng phương thức JavaScript như HTMLElement.togglePopover(), thuộc tính sourcenull.

Ví dụ

Sử dụng cơ bản của source

Bản demo này cho thấy cách sử dụng thuộc tính source để thực hiện các hành động khác nhau dựa trên nút điều khiển đóng phần tử popover.

HTML

html
<button commandfor="popover" command="show-popover">
  Select cookie preference
</button>
<p id="output"></p>
<div id="popover" popover="auto">
  <h3>Would you like a cookie?</h3>
  <button id="yes" commandfor="popover" command="hide-popover">Yes</button>
  <button id="no" commandfor="popover" command="hide-popover">No</button>
</div>

JavaScript

js
const yesBtn = document.getElementById("yes");
const noBtn = document.getElementById("no");
const popover = document.getElementById("popover");
const output = document.getElementById("output");
js
if (yesBtn.command === undefined) {
  output.textContent = "Popover control command attribute not supported.";
} else {
  popover.addEventListener("toggle", (event) => {
    if (event.source === undefined) {
      output.textContent = "ToggleEvent.source not supported.";
    } else if (event.source === yesBtn) {
      output.textContent = "Cookie set!";
    } else if (event.source === noBtn) {
      output.textContent = "No cookie set.";
    }
  });
}

Kết quả

Thông số kỹ thuật

Specification
HTML
# dom-toggleevent-source

Tương thích trình duyệt

Xem thêm