大网数据广告活动
Web 标准与前端开发

CommandEvent

· 52CE 我爱测

`CommandEvent`** 接口表示一个事件,当拥有有效的 HTMLButtonElement.commandForElement 和 HTMLButtonElement.command 属性的 HTMLButtonElement 元素即将调用一个交互元素时,该事件会通知用户。

Invoker Commands API

CommandEvent 接口表示一个事件,当拥有有效的 HTMLButtonElement.commandForElement 和 HTMLButtonElement.command 属性的 HTMLButtonElement 元素即将调用一个交互元素时,该事件会通知用户。

它是 HTMLElement 的 HTMLElement.command_event 事件的事件对象,表示当调用者控件被激活时的操作(例如点击或按下)。

构造函数

  • CommandEvent.CommandEvent
    • : 创建一个 CommandEvent 对象。

实例属性

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

  • CommandEvent.source
    • : 表示触发此次调用的按钮的 HTMLButtonElement。
  • CommandEvent.command
    • : 表示源按钮的 HTMLButtonElement.command 属性值的字符串。

示例

基本示例

<button commandfor="mypopover" command="show-popover">显示弹出框</button>

<div popover id="mypopover" role="[声明合适的 ARIA 角色]">
  
  <button commandfor="mypopover" command="hide-popover">隐藏弹出框</button>
</div>
const popover = document.getElementById("mypopover");

// …

popover.addEventListener("command", (event) => {
  if (event.command === "show-popover") {
    console.log("弹出框即将显示");
  }
});

使用自定义命令值

此实例使用带有自定义值的 commands 创建了三个按钮。

<div class="controls">
  <button commandfor="the-image" command="--rotate-left">左旋转</button>
  <button commandfor="the-image" command="--reset">重置</button>
  <button commandfor="the-image" command="--rotate-right">右旋转</button>
</div>

<img
  id="the-image"
  src="/shared-assets/images/examples/dino.svg"
  alt="恐龙头部旋转了 0 度" />
.controls {
  margin-block-end: 20px;
}

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

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 = `恐龙头部旋转了 ${rotate} 度`;
});

使用自定义命令值

规范

浏览器兼容性

参见

  • Invoker Commands API
  • HTMLButtonElement.command
  • HTMLButtonElement.commandForElement

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。