CommandEvent

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

CommandEvent 接口表示当带有有效 commandForElementcommand 属性的 button 元素即将调用交互式元素时通知用户的事件。

这是 HTMLElement command 事件的事件对象,它表示从调用方控件(例如,当它被点击或按下时)发出的一个操作。

Event CommandEvent

构造函数

CommandEvent()

创建一个 CommandEvent 对象。

实例属性

此接口继承了其父接口 Event 的属性。

CommandEvent.source 只读

一个 HTMLButtonElement,表示导致此调用的按钮。

CommandEvent.command 只读

一个字符串,表示源按钮的 command 值。

示例

基本示例

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");
  }
});

为命令使用自定义值

在此示例中,已使用 带有自定义值的命令 创建了三个按钮。

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" />

使用 command 事件 将事件监听器附加到图片上。当其中一个按钮被点击时,监听器将根据分配给按钮的自定义 command 值运行代码,旋转图片,并更新其 alt 文本以指示图片的新角度。

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`;
});

规范

规范
HTML
# commandevent

浏览器兼容性

另见