HTMLButtonElement:command 屬性
HTMLButtonElement 介面的 command 屬性獲取和設定此按鈕所控制元素將要執行的操作。要使其生效,必須設定 commandfor。
它反映了 command HTML 屬性。
值
一個字串。有關有效值,請參閱 command 屬性。
示例
基本示例
html
<button id="toggleBtn" commandfor="mypopover" command="toggle-popover">
Toggle popover
</button>
<div popover id="mypopover">
<button commandfor="mypopover" command="hide-popover">Hide popover</button>
</div>
js
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");
toggleBtn.command = "show-popover";
使用自定義命令值
在此示例中,建立了三個按鈕,使用了 command 的自定義值。每個按鈕都使用 commandfor 屬性指向同一影像。
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 # dom-button-command |
瀏覽器相容性
載入中…