Invoker Commands API
Invoker Commands API 提供了一种声明式地将行为分配给按钮的方法,允许在用户操作按钮时(例如单击或通过键盘按下空格键或回车键)控制交互式元素。
概念与用法
Web 上常见的模式是使用 <button>
元素来控制页面的各个方面,例如打开和关闭 弹出式菜单 或 <dialog>
元素,格式化文本等。
传统上,创建这类控件需要将 JavaScript 事件监听器添加到按钮上,然后该监听器可以调用它们所控制元素的 API。 commandForElement
和 command
属性提供了一种为有限集的操作以声明式方式完成此操作的方法。这对于内置命令很有优势,因为用户不必等待 JavaScript 下载和执行即可使这些按钮具有交互性。
HTML 属性
commandfor
-
将
<button>
元素转换为按钮,控制指定的交互式元素;其值是待控制元素的 ID。 command
-
指定由
commandfor
属性指定的、由<button>
控件执行的操作。
接口
CommandEvent
-
表示一个通知用户命令已发出的事件。它是
command
事件的事件对象。该事件在由commandForElement
引用的元素上触发。
其他接口的扩展
实例属性
-
获取和设置按钮所控制的元素。是
commandfor
HTML 属性的 JavaScript 等效项。 -
获取和设置按钮所控制的元素上要执行的操作。反映
command
HTML 属性的值。
事件
command
事件-
在按钮引用的元素上触发。
示例
创建声明式弹出式菜单
html
<button commandfor="mypopover" command="toggle-popover">
Toggle the popover
</button>
<div id="mypopover" popover>
<button commandfor="mypopover" command="hide-popover">Close</button>
Popover content
</div>
创建声明式对话框
html
<button commandfor="mydialog" command="show-modal">Show modal dialog</button>
<dialog id="mydialog">
<button commandfor="mydialog" command="close">Close</button>
Dialog Content
</dialog>
创建自定义命令
html
<button commandfor="my-img" command="--rotate-left">Rotate left</button>
<button commandfor="my-img" command="--rotate-right">Rotate right</button>
<img id="my-img" src="photo.jpg" alt="[add appropriate alt text here]" />
js
const myImg = document.getElementById("my-img");
myImg.addEventListener("command", (event) => {
if (event.command === "--rotate-left") {
myImg.style.rotate = "-90deg";
} else if (event.command === "--rotate-right") {
myImg.style.rotate = "90deg";
}
});
规范
规范 |
---|
HTML # commandevent |
HTML # dom-button-commandforelement |
HTML # dom-button-command |
浏览器兼容性
api.CommandEvent
加载中…
api.HTMLButtonElement.commandForElement
加载中…
api.HTMLButtonElement.command
加载中…
另见
command
属性commandForElement
属性CommandEvent
接口