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

另見