← 中文资源

简体中文版本

用原生 details 与 summary 构建 FAQ

用 details 与 summary 实现可折叠问答,保留标题结构,并依赖浏览器原生的展开状态播报。

阅读英文原文

题目

FAQ 页面需要三个可折叠问答。每个问题要保留在标题大纲中,键盘与屏幕阅读器用户无需 JavaScript 就能展开和收起。要求使用原生 disclosure 元素,而不是用 div 自行拼接。

  • 输入:三个关于复制示例的问答对。
  • 输出:由 details 与 summary 组成的可折叠列表。
  • 公开样例:聚焦已收起的 summary 时播报 collapsed 与问题文本;按 Enter 或 Space 切换展开状态。

解题思路

details 自带展开和收起状态、键盘处理与语义,summary 是它的控制元素,其内容就是可访问名称,因此不要再加 role="button" 或 aria-expanded。把问题包在 h3 中放进 summary,HTML 允许 summary 包含标题内容,这样页面大纲仍能列出每个问题。答案作为 summary 之后的普通内容,随 disclosure 一起显示或隐藏。外层用 section 并通过 aria-labelledby 关联 FAQ 标题,形成可识别区域。

参考实现要点

  1. 每个问答写成 details 包裹 summary(内含 h3)与答案段落。
  2. summary 必须是对应 details 的第一个子元素。
  3. 三个问题保持同级、不嵌套,避免出现多层 disclosure。
  4. 外层 section 设置 aria-labelledby="faq-heading",标题为 h2。
  5. 不添加任何点击事件处理或 ARIA 状态属性。

常见错误

  • 给 summary 加 role="button" 和 aria-expanded,与原生语义重复,状态容易不同步。
  • 用 div 加 click 监听模拟折叠,键盘无法操作,屏幕阅读器也拿不到展开状态。
  • 把答案写进 summary,收起时答案仍会被朗读。
  • 给 summary 设置 display:flex 后丢失默认的三角标记与部分键盘行为。

验证方式

用 Tab 聚焦任一 summary,分别按 Enter 与 Space,确认答案展开和收起且焦点保持在原处。在无障碍树中检查 summary 暴露展开状态,名称为问题标题。刷新后确认默认全部收起。最后禁用 JavaScript,折叠行为应完全正常。

代码示例

<section aria-labelledby="faq-heading">
  <h2 id="faq-heading">Frequently asked questions</h2>

  <details>
    <summary><h3>Do I need an account to copy an example?</h3></summary>
    <p>No. Every example is public and ready to copy without signing in.</p>
  </details>

  <details>
    <summary><h3>Can I use the examples in commercial projects?</h3></summary>
    <p>Yes. The snippets are released under the MIT license, so attribution is optional.</p>
  </details>

  <details>
    <summary><h3>Why does a snippet use an older API?</h3></summary>
    <p>Each page lists a version note when the API changed; open an issue if a note is missing.</p>
  </details>
</section>