HTMLDetailsElement

HTMLDetailsElement 接口提供了操作 <details> 元素的特殊属性(除了它通过继承获得的常规 HTMLElement 接口之外)。

EventTarget Node Element HTMLElement HTMLDetailsElement

实例属性

继承自其父级 HTMLElement 的属性。

HTMLDetailsElement.name

一个反映 name HTML 属性的字符串,它允许你创建一组互斥的 <details> 元素。打开此组中命名的一个 <details> 元素会导致该组中的其他元素关闭。

HTMLDetailsElement.open

一个反映 open HTML 属性的布尔值,指示该元素的(不包括 <summary>)内容是否应显示给用户。

实例方法

无特定方法;从其父级 HTMLElement 继承方法。

事件

从其父接口 HTMLElement 继承事件。

示例

打开和关闭章节时记录日志

此示例使用 HTMLElementtoggle 事件,在章节打开和关闭时将其添加到日志侧边栏或从中移除。

HTML

html
<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>
<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>

CSS

css
body {
  display: flex;
}

#log {
  flex-shrink: 0;
  padding-left: 3em;
}

#summaries {
  flex-grow: 1;
}

JavaScript

js
function logItem(e) {
  console.log(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
# htmldetailselement
HTML
# event-toggle

浏览器兼容性

api.HTMLDetailsElement

api.HTMLElement.toggle_event.details_elements

另见