HTMLDialogElement: requestClose() 方法

基准线 2025
新推出

自 2025 年 5 月起,此功能适用于最新的设备和浏览器版本。此功能可能不适用于较旧的设备或浏览器。

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

此方法与 HTMLDialogElement.close() 方法的不同之处在于,它在触发 close 事件之前会触发一个 cancel 事件。开发者可以在 cancel 事件的处理程序中调用 Event.preventDefault() 来阻止对话框关闭。

此方法暴露的行为与对话框的内部关闭观察器相同。

语法

js
requestClose()
requestClose(returnValue)

参数

returnValue 可选

一个字符串,表示对话框的 HTMLDialogElement.returnValue 的更新值。

返回值

无(undefined)。

示例

使用 requestClose()

以下示例展示了一个简单的按钮,当点击该按钮时,会通过 showModal() 方法打开一个包含表单的 <dialog> 元素。打开后,您可以点击 **X** 按钮(通过 HTMLDialogElement.requestClose() 方法)请求关闭对话框,或通过 **Confirm** 按钮提交表单。

HTML

html
<!-- Simple pop-up dialog box, containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <button type="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>

JavaScript

js
const updateButton = document.getElementById("updateDetails");
const closeButton = document.getElementById("close");
const dialog = document.getElementById("favDialog");

// Update button opens a modal dialog
updateButton.addEventListener("click", () => {
  dialog.showModal();
});

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

function dialogShouldNotClose() {
  // Add logic to decide whether to allow the dialog to close.
  // Closing prevented by default
  return true;
}

dialog.addEventListener("cancel", (event) => {
  if (!event.cancelable) return;
  if (dialogShouldNotClose()) {
    console.log("Closing prevented");
    event.preventDefault();
  }
});

如果“X”按钮的 type 为“submit”,则无需 JavaScript 即可关闭对话框。表单提交会关闭其嵌套的 <dialog> 元素,前提是 表单的 methoddialog,因此不需要“关闭”按钮。

结果

规范

规范
HTML
# dom-dialog-requestclose

浏览器兼容性

另见

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