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

浏览器兼容性

另见