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

<details></details> 和 <summary></summary> 是实现 FAQ 折叠布局最轻量、语义化最强的原生方案,现代浏览器(Chrome 12+、Firefox 49+、Safari 6.1+、Edge 79+)已全面支持,无需 JS 就能完成基础交互与无障碍支持。
为什么直接用 <details></details> 有时点不动?
常见原因是结构不合规,浏览器会静默忽略交互逻辑,且不报错。必须严格满足以下三点:
-
<summary></summary>必须是<details></details>的**直接子元素**,且是**第一个子元素** -
<summary></summary>内只能包含内联元素(如<strong></strong>、<em></em>、文本),不能含<p></p>、<div>、<code><span></span>等块级或嵌套容器 - 中间不能插入任何包裹标签(例如
<div><summary>...</summary></div>)——这会导致点击无响应 - 用
toggle而非click:它能捕获键盘操作(空格/回车),且在open属性变更后触发,状态准确 - 只在
e.target.open === true时执行关闭逻辑,避免收起时误触发二次操作 - 新动态插入的
<details></details>需重新绑定,或改用事件委托(监听父容器)
错误示例:<details><div><summary>Q?</summary></div>
<p>A</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/code/12093" title="CSS婚礼策划服务机构宣传网站模板"><img
src="https://img.php.cn/upload/webcode/000/000/018/178607072210981.jpg" alt="CSS婚礼策划服务机构宣传网站模板" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/code/12093" title="CSS婚礼策划服务机构宣传网站模板" class="overflowclass">CSS婚礼策划服务机构宣传网站模板</a>
<p class="overflowclass">CSS婚礼策划服务机构宣传网站模板是一款适合提供婚礼策划和婚庆服务机构宣传网站模板下载。提示:本模板调用到谷歌字体库,可能会出现页面打开比较缓慢。</p>
</div>
<a rel="nofollow" href="/xiazai/code/12093" title="CSS婚礼策划服务机构宣传网站模板" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div></details>;正确写法应为:<details><summary>Q?</summary><p>A</p></details>
如何让多个 FAQ 项互斥展开(手风琴效果)?
<details></details> 默认各自独立,要实现“点开一个、其他自动收起”,必须用 JS 监听 toggle 事件(不是 click):
简短可用代码:
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></details> 原生不支持 CSS 过渡,height: auto 也无法 transition。唯一可靠路径是绕过它,用 max-height 控制一个内部容器:
- 不要对
<details></details>或<summary></summary>直接设max-height—— 浏览器会忽略 - 把答案内容包进一个
<div class="faq-content">,对它设 <code>max-height+overflow: hidden+transition -
max-height值需保守估算(如600px),太小会截断,太大则收起拖沓 - 用
<details>[open] .faq-content</details>触发展开样式,保留语义和键盘支持
关键 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></details> 只管状态与可访问性,max-height 只管动效。混在一起既难调试,又会在 Safari 等浏览器中失效。










