<details>和<summary>是实现FAQ折叠最轻量、语义化最强的原生方案,需确保<summary>为<details>直接且首个子元素、仅含内联内容;手风琴效果须用toggle事件监听并手动关闭其他项;平滑动画需通过max-height控制内部容器,与语义结构解耦。

<details> 和 <summary> 是实现 FAQ 折叠布局最轻量、语义化最强的原生方案,现代浏览器(Chrome 12+、Firefox 49+、Safari 6.1+、Edge 79+)已全面支持,无需 JS 就能完成基础交互与无障碍支持。
为什么直接用 <details> 有时点不动?
常见原因是结构不合规,浏览器会静默忽略交互逻辑,且不报错。必须严格满足以下三点:
-
<summary>必须是<details>的**直接子元素**,且是**第一个子元素** -
<summary>内只能包含内联元素(如<strong>、<em>、文本),不能含<p>、<div>、<span>等块级或嵌套容器 - 中间不能插入任何包裹标签(例如
<div><summary>...</summary></div>)——这会导致点击无响应
错误示例:<details><div><summary>Q?</summary></div><p>A</p></details>;正确写法应为:<details><summary>Q?</summary><p>A</p></details>
如何让多个 FAQ 项互斥展开(手风琴效果)?
<details> 默认各自独立,要实现“点开一个、其他自动收起”,必须用 JS 监听 toggle 事件(不是 click):
立即学习“前端免费学习笔记(深入)”;
- 用
toggle而非click:它能捕获键盘操作(空格/回车),且在open属性变更后触发,状态准确 - 只在
e.target.open === true时执行关闭逻辑,避免收起时误触发二次操作 - 新动态插入的
<details>需重新绑定,或改用事件委托(监听父容器)
简短可用代码:
document.querySelectorAll('.faq-item').forEach(item => {
item.addEventListener('toggle', e => {
if (!e.target.open) return;
document.querySelectorAll('.faq-item').forEach(other => {
if (other !== e.target) other.open = false;
});
});
});
怎么加平滑展开动画?
<details> 原生不支持 CSS 过渡,height: auto 也无法 transition。唯一可靠路径是绕过它,用 max-height 控制一个内部容器:
- 不要对
<details>或<summary>直接设max-height—— 浏览器会忽略 - 把答案内容包进一个
<div class="faq-content">,对它设max-height+overflow: hidden+transition -
max-height值需保守估算(如600px),太小会截断,太大则收起拖沓 - 用
<details>[open] .faq-content触发展开样式,保留语义和键盘支持
关键 CSS 片段:
.faq-content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease, opacity 0.2s ease;
}
details[open] .faq-content {
max-height: 600px;
opacity: 1;
}
真正容易被忽略的是:动画逻辑和语义结构必须解耦——<details> 只管状态与可访问性,max-height 只管动效。混在一起既难调试,又会在 Safari 等浏览器中失效。


















