1. 給開發者的 Web 技術文件
  2. Web API
  3. HTMLDialogElement
  4. close

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in English Always switch to English

HTMLDialogElement:close 事件

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2022年3月.

close 事件會在 HTMLDialogElement 物件所代表的 <dialog> 被關閉時,在該物件上觸發。

此事件不可取消,且不會冒泡。

語法

addEventListener() 等方法中使用事件名稱,或設定事件處理器屬性。

js
addEventListener("close", (event) => { })
onclose = (event) => { }

事件類型

通用的 Event

範例

即時範例

HTML

html
<dialog class="example-dialog">
 <form method="dialog">
 <button>透過 method="dialog" 關閉</button>
 </form>
 <button class="close">透過 .close() 方法關閉</button>
 <p>或按下 <kbd>Esc</kbd> 鍵</p>
</dialog>
<button class="open-dialog">開啟對話方塊</button>
<div class="result"></div>
button,
div {
 margin: 0.5rem;
}

JavaScript

js
const result = document.querySelector(".result");
const dialog = document.querySelector(".example-dialog");
dialog.addEventListener("close", (event) => {
 result.textContent = "對話方塊已關閉";
});
const openDialog = document.querySelector(".open-dialog");
openDialog.addEventListener("click", () => {
 dialog.showModal();
 result.textContent = "";
});
const closeButton = document.querySelector(".close");
closeButton.addEventListener("click", () => {
 dialog.close();
});

結果

規範

Specification
HTML
# event-close

瀏覽器相容性

參見

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /