Invoker Commands API

Invoker Commands API 提供了一種宣告式地將行為分配給按鈕的方法,允許在使用者操作按鈕時(例如單擊或透過鍵盤按下空格鍵或回車鍵)控制互動式元素。

概念與用法

Web 上常見的模式是使用 <button> 元素來控制頁面的各個方面,例如開啟和關閉 彈出式選單<dialog> 元素,格式化文字等。

傳統上,建立這類控制元件需要將 JavaScript 事件監聽器新增到按鈕上,然後該監聽器可以呼叫它們所控制元素的 API。 commandForElementcommand 屬性提供了一種為有限集的操作以宣告式方式完成此操作的方法。這對於內建命令很有優勢,因為使用者不必等待 JavaScript 下載和執行即可使這些按鈕具有互動性。

HTML 屬性

commandfor

<button> 元素轉換為按鈕,控制指定的互動式元素;其值是待控制元素的 ID。

command

指定由 commandfor 屬性指定的、由 <button> 控制元件執行的操作。

介面

CommandEvent

表示一個通知使用者命令已發出的事件。它是 command 事件的事件物件。該事件在由 commandForElement 引用的元素上觸發。

其他介面的擴充套件

例項屬性

HTMLButtonElement.commandForElement

獲取和設定按鈕所控制的元素。是 commandfor HTML 屬性的 JavaScript 等效項。

HTMLButtonElement.command

獲取和設定按鈕所控制的元素上要執行的操作。反映 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

另見