HTMLDetailsElement:toggle 事件
當 <details> 元素的 open/closed 狀態切換時,將觸發 toggle 事件。
此事件不可取消,也不會冒泡。
注意:toggle 事件在 HTMLElement 上也以不同的形式提供;此版本在 彈出視窗元素 顯示或隱藏後立即觸發。有關更多資訊,請參閱 HTMLElement toggle 事件頁面。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("toggle", (event) => {});
ontoggle = (event) => {};
html
<details ontoggle="console.log(this.open)" open>...</details>
注意:在上面的示例中,由於設定了 open 屬性,因此事件監聽器將在沒有任何使用者互動的情況下被呼叫一次。不建議使用這種 事件處理程式屬性。
事件型別
一個 ToggleEvent。繼承自 Event。
示例
此示例記錄開啟的章節。當章節關閉時,它們將從日誌中刪除。
HTML
html
<aside id="log">
<p>Open chapters:</p>
<div data-id="ch1" hidden>I</div>
<div data-id="ch2" hidden>II</div>
<div data-id="ch3" hidden>III</div>
</aside>
<section id="summaries">
<p>Chapter summaries:</p>
<details id="ch1">
<summary>Chapter I</summary>
Philosophy reproves Boethius for the foolishness of his complaints against
Fortune. Her very nature is caprice.
</details>
<details id="ch2">
<summary>Chapter II</summary>
Philosophy in Fortune's name replies to Boethius' reproaches, and proves
that the gifts of Fortune are hers to give and to take away.
</details>
<details id="ch3">
<summary>Chapter III</summary>
Boethius falls back upon his present sense of misery. Philosophy reminds him
of the brilliancy of his former fortunes.
</details>
</section>
CSS
css
body {
display: flex;
flex-direction: row-reverse;
}
#log {
flex-shrink: 0;
padding-left: 3em;
}
#summaries {
flex-grow: 1;
}
JavaScript
js
function logItem(e) {
const item = document.querySelector(`[data-id=${e.target.id}]`);
item.toggleAttribute("hidden");
}
const chapters = document.querySelectorAll("details");
chapters.forEach((chapter) => {
chapter.addEventListener("toggle", logItem);
});
結果
規範
| 規範 |
|---|
| HTML 標準 # event-toggle |
瀏覽器相容性
BCD 表格僅在啟用 JavaScript 的瀏覽器中載入。