toggle event fires when the open / closed state of a <details> element is toggled.

冒泡 No
可取消 No
接口 事件
事件处理程序特性 None
默认动作 Toggles the open state of the <details> 元素。

范例

This example logs chapters that are open. Chapters are removed from the log when they are closed.

HTML

<aside id="log">
  <b>Open chapters:</b>
  <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">
  <b>Chapter summaries:</b>
  <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

body {
  display: flex;
  flex-direction: row-reverse;
}
#log {
  flex-shrink: 0;
  padding-left: 3em;
}
#summaries {
  flex-grow: 1;
}
					

JavaScript

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 实时标准
The definition of 'toggle event' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
toggle event Chrome Yes Edge ≤79 Firefox Yes IE ? Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android Yes Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

兼容性未知 ?

兼容性未知

元数据

  • 最后修改:
  1. HTMLDetailsElement
  2. 事件
    1. toggle