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>