CommandEvent
CommandEvent 介面表示當帶有有效 commandForElement 和 command 屬性的 button 元素即將呼叫互動式元素時通知使用者的事件。
這是 HTMLElement command 事件的事件物件,它表示從呼叫方控制元件(例如,當它被點選或按下時)發出的一個操作。
建構函式
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 |
瀏覽器相容性
載入中…