CommandEvent
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
CommandEvent 接口表示一个事件,当拥有有效的 commandForElement 和 command 属性的 button 元素即将调用一个交互元素时,该事件会通知用户。
它是 HTMLElement 的 command 事件的事件对象,表示当调用者控件被激活时的操作(例如点击或按下)。
构造函数
CommandEvent()-
创建一个
CommandEvent对象。
实例属性
此接口继承其父接口 Event 的属性。
CommandEvent.source只读-
表示触发此次调用的按钮的
HTMLButtonElement。 CommandEvent.command只读-
表示源按钮的
command属性值的字符串。
示例
>基本示例
html
<button commandfor="mypopover" command="show-popover">显示弹出框</button>
<div popover id="mypopover" role="[声明合适的 ARIA 角色]">
<!-- 弹出框内容 -->
<button commandfor="mypopover" command="hide-popover">隐藏弹出框</button>
</div>
js
const popover = document.getElementById("mypopover");
// …
popover.addEventListener("command", (event) => {
if (event.command === "show-popover") {
console.log("弹出框即将显示");
}
});
使用自定义命令值
此实例使用带有自定义值的 commands 创建了三个按钮。
html
<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 度" />
使用 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 = `恐龙头部旋转了 ${rotate} 度`;
});
规范
| Specification |
|---|
| HTML> # commandevent> |