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>