--- title: 'HTMLDetailsElement: toggle event' slug: Web/API/HTMLDetailsElement/toggle_event translation_of: Web/API/HTMLDetailsElement/toggle_event --- <div> <p>{{APIRef}}</p> <p>当{{HtmlElement("details")}}元素<code>打开</code>/<code>关闭</code>状态被切换时,切换事件会触发。</p> <table> <tbody> <tr> <th>Bubbles</th> <td>No</td> </tr> <tr> <th>Cancelable</th> <td>No</td> </tr> <tr> <th>Interface</th> <td>{{DOMxRef("Event")}}</td> </tr> <tr> <th>Event handler property</th> <td>None</td> </tr> <tr> <th>Default Action</th> <td>Toggles the <code>open</code> state of the {{HtmlElement("details")}} element.</td> </tr> </tbody> </table> <h2 id="例子">例子</h2> <p>此示例记录打开的章节。 当章节关闭时,它们将从日志中删除。</p> <h3 id="HTML">HTML</h3> <pre class="notranslate"><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></pre> <h3 id="CSS">CSS</h3> <pre class="notranslate">body { display: flex; flex-direction: row-reverse; } #log { flex-shrink: 0; padding-left: 3em; } #summaries { flex-grow: 1; }</pre> <h3 id="JavaScript">JavaScript</h3> <pre class="notranslate">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); });</pre> <h3 id="Result">Result</h3> <p>{{EmbedLiveSample("Examples", 700, 200)}}</p> <h2 id="规范">规范</h2> <table> <thead> <tr> <th scope="col">Specification</th> <th scope="col">Status</th> <th scope="col">Comment</th> </tr> </thead> <tbody> <tr> <td>{{SpecName('HTML WHATWG', 'indices.html#event-toggle', 'toggle event')}}</td> <td>{{Spec2("HTML WHATWG")}}</td> <td></td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> <p>{{Compat("api.HTMLDetailsElement.toggle_event")}}</p> </div>