HTMLDialogElement: show() 方法

Baseline 已广泛支持

此特性已经十分成熟,可在许多设备和浏览器版本上使用。自 2022 年 3 月起,它已在各浏览器中可用。

HTMLDialogElement 接口的 show() 方法以非模态方式显示对话框,即仍然允许与对话框外的其他内容进行交互。

语法

js
show()

参数

无。

返回值

无(undefined)。

异常

InvalidStateError DOMException

如果对话框已打开且为模态(即,如果对话框已通过 HTMLDialogElement.showModal() 打开),则会抛出此错误。

示例

以下示例展示了一个简单的按钮,当点击该按钮时,将通过 show() 方法打开一个包含表单的 <dialog> 元素。然后,您可以点击取消按钮(通过 HTMLDialogElement.close() 方法)关闭对话框,或通过提交按钮提交表单。

html
<!-- Simple pop-up dialog box, containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <section>
      <p>
        <label for="favAnimal">Favorite animal:</label>
        <select id="favAnimal" name="favAnimal">
          <option></option>
          <option>Brine shrimp</option>
          <option>Red panda</option>
          <option>Spider monkey</option>
        </select>
      </p>
    </section>
    <menu>
      <button id="cancel" type="reset">Cancel</button>
      <button type="submit">Confirm</button>
    </menu>
  </form>
</dialog>

<menu>
  <button id="updateDetails">Update details</button>
</menu>
js
const updateButton = document.getElementById("updateDetails");
const cancelButton = document.getElementById("cancel");
const dialog = document.getElementById("favDialog");
dialog.returnValue = "favAnimal";

function openCheck(dialog) {
  if (dialog.open) {
    console.log("Dialog open");
  } else {
    console.log("Dialog closed");
  }
}

// Update button opens a modeless dialog
updateButton.addEventListener("click", () => {
  dialog.show();
  openCheck(dialog);
});

// Form cancel button closes the dialog box
cancelButton.addEventListener("click", () => {
  dialog.close("animalNotChosen");
  openCheck(dialog);
});

规范

规范
HTML
# dom-dialog-show-dev

浏览器兼容性

另见

  • 实现此接口的 HTML 元素:<dialog>