details标签无法直接用css过渡动画,因open属性不可动画;可靠方案是js监听toggle事件,用max-height配合scrollheight实现展开收缩动画,并注意图片加载和响应式处理。

details 标签本身不支持 CSS 过渡动画
直接给 details 或 summary 加 transition 没用,因为它的展开/收起是通过 open 属性切换的,而该属性本身不是 CSS 可动画属性(比如不能对 open 做 transition: open 0.3s)。浏览器也不触发 height、opacity 等常规过渡所需的 DOM 状态变化。
用 JavaScript 监听 open/close 并手动控制高度过渡
这是目前最可靠、兼容性好(IE11+ 也行)的做法:监听 toggle 事件,读取 details 内容区(即 details > * 中第一个非 summary 元素)的滚动高度,再用 max-height + transition 模拟展开收缩。
关键点:
- 必须用
max-height(不是height),因为内容高度不确定 - 初始
max-height设为0,展开时设为内容实际scrollHeight - 过渡结束后要清除内联
max-height,避免影响响应式或 JS 重置 - 注意处理内容中图片未加载完成导致
scrollHeight计算偏小的问题(可加img.onload后重算)
简短示例:
const details = document.querySelector('details');
const content = details.querySelector(':scope > *:not(summary)');
<p>details.addEventListener('toggle', () => {
if (details.open) {
content.style.maxHeight = content.scrollHeight + 'px';
} else {
content.style.maxHeight = '0';
}
});</p><p>// CSS 需配:
// details > *:not(summary) { transition: max-height 0.3s ease-in-out; overflow: hidden; }
</p>
用 CSS @starting-style + animation(Chrome 114+ 实验性支持)
这是原生方案,但目前仅 Chrome 最新稳定版部分支持,且需开启实验性 flag(chrome://flags/#enable-css-animation-starting-style),生产环境别用。
它允许你写:
@starting-style {
details[open] > *:not(summary) {
max-height: 0;
}
}
details[open] > *:not(summary) {
max-height: 500px; /* 必须是固定值,不能用 fit-content */
transition: max-height 0.3s;
}
问题很明显:max-height 得预设上限,内容超了会截断;@starting-style 兼容性极差;无法动态读取 scrollHeight。
为什么不用 height: auto + transition?
因为 height: auto 无法参与 CSS 过渡——浏览器不知道“auto”对应多少像素,transition 会直接跳变。你可能会看到第一帧闪一下,或者完全没动画。
常见错误写法:
details[open] > *:not(summary) {
height: auto; /* ❌ 这里不会动起来 */
transition: height 0.3s;
}
替代思路只有两个:用 max-height(推荐),或改用 transform: scaleY() + overflow: hidden(但会引发子元素定位/焦点问题,慎用)。
真正要注意的是:每次展开前确保内容已渲染完毕(比如异步加载的内容要等数据插入 DOM 后再触发 open),否则 scrollHeight 读出来是 0。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











