CommandEvent

Baseline 2025
Newly available

Since December 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Giao diện CommandEvent biểu diễn một sự kiện thông báo cho người dùng khi một phần tử button có các thuộc tính commandForElementcommand hợp lệ sắp gọi một phần tử tương tác.

Đây là đối tượng sự kiện cho sự kiện command của HTMLElement command, biểu diễn một hành động từ một Invoker Control khi nó được kích hoạt (ví dụ khi được nhấp hoặc nhấn).

Event CommandEvent

Constructor

CommandEvent()

Tạo một đối tượng CommandEvent.

Thuộc tính thể hiện

Giao diện này kế thừa các thuộc tính từ đối tượng cha của nó, Event.

CommandEvent.source Read only

Một HTMLButtonElement biểu diễn nút đã gây ra lần gọi này.

CommandEvent.command Read only

Một chuỗi biểu diễn giá trị command của nút nguồn.

Ví dụ

Ví dụ cơ bản

html
<button commandfor="mypopover" command="show-popover">Show popover</button>

<div popover id="mypopover" role="[declare appropriate ARIA role]">
  <!-- popover content here -->
  <button commandfor="mypopover" command="hide-popover">Hide popover</button>
</div>
js
const popover = document.getElementById("mypopover");

// …

popover.addEventListener("command", (event) => {
  if (event.command === "show-popover") {
    console.log("Popover is about to be shown");
  }
});

Dùng giá trị tùy chỉnh cho các lệnh

Trong ví dụ này, ba nút được tạo với command có giá trị tùy chỉnh.

html
<div class="controls">
  <button commandfor="the-image" command="--rotate-left">Rotate Left</button>
  <button commandfor="the-image" command="--reset">Reset</button>
  <button commandfor="the-image" command="--rotate-right">Rotate Right</button>
</div>

<img
  id="the-image"
  src="/shared-assets/images/examples/dino.svg"
  alt="dinosaur head rotated 0 degrees" />

Một trình lắng nghe sự kiện được gắn vào hình ảnh bằng sự kiện command. Khi một trong các nút được nhấp, trình lắng nghe sẽ chạy mã dựa trên giá trị command tùy chỉnh được gán cho nút, xoay hình ảnh và đồng thời cập nhật văn bản alt của nó để cho biết góc mới của hình ảnh.

js
const image = document.getElementById("the-image");

image.addEventListener("command", (event) => {
  let rotate = parseInt(event.target.style.rotate || "0", 10);
  if (event.command === "--reset") {
    rotate = 0;
    event.target.style.rotate = `${rotate}deg`;
  } else if (event.command === "--rotate-left") {
    rotate = rotate === -270 ? 0 : rotate - 90;
    event.target.style.rotate = `${rotate}deg`;
  } else if (event.command === "--rotate-right") {
    rotate = rotate === 270 ? 0 : rotate + 90;
    event.target.style.rotate = `${rotate}deg`;
  }
  event.target.alt = `dinosaur head rotated ${rotate} degrees`;
});

Thông số kỹ thuật

Specification
HTML
# commandevent

Khả năng tương thích với trình duyệt

Xem thêm