HTMLDialogElement: close() 方法

Baseline 已广泛支持

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

HTMLDialogElement 接口的 close() 方法用于关闭 <dialog> 元素。可以传递一个可选的字符串作为参数,用于更新对话框的 returnValue

语法

js
close()
close(returnValue)

参数

returnValue 可选

一个字符串,表示 HTMLDialogElement.returnValue 的新值。

返回值

无(undefined)。

示例

以下示例展示了一个简单的按钮,点击该按钮会通过 showModal() 方法打开一个包含表单的 <dialog> 元素。在那里,你可以点击“X”按钮(通过 HTMLDialogElement.close() 方法)关闭对话框,或者通过提交按钮提交表单。

html
<!-- Simple pop-up dialog box, containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <button id="close" aria-label="close" formnovalidate>X</button>
    <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 type="reset">Reset</button>
      <button type="submit">Confirm</button>
    </menu>
  </form>
</dialog>

<menu>
  <button id="updateDetails">Update details</button>
</menu>
js
const updateButton = document.getElementById("updateDetails");
const closeButton = document.getElementById("close");
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 modal dialog
updateButton.addEventListener("click", () => {
  dialog.showModal();
  openCheck(dialog);
});

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

如果“X”按钮的 type 为 "submit",那么在没有 JavaScript 的情况下,对话框就会关闭。当一个表单的 method 设置为 dialog 时,表单提交会关闭其嵌套的 <dialog> 元素,因此不需要“关闭”按钮。

结果

规范

规范
HTML
# dom-dialog-close-dev

浏览器兼容性

另见

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