本文详解如何通过 css `height` 和 `overflow: hidden` 配合 `transition` 实现真正的可折叠容器展开/收起动画,避开 `display: none` 导致过渡失效的常见误区,并提供简洁可靠的 html/css/js 实现方案。
CSS 的 transition 属性无法在 display: none 与 display: block(或其他值)之间产生过渡效果——因为 display 是一个离散的、非连续的属性,浏览器无法计算“半隐藏”状态,因此任何涉及 display 切换的动画都会表现为突兀的跳变。
要实现 Obsidian 风格的平滑折叠动画,核心原则是:仅对可插值的连续属性(如 height、opacity、max-height)应用过渡,并配合 overflow: hidden 截断溢出内容。
以下是一个精简、可复用的实现示例:
Click To Open
I am Text! In fact I am so much text that I make the Foldable Container Div Larger!
.container {
padding: 50px;
width: 200px;
background: #affaf7;
}
#foldable-content {
background-color: #8fbdbb;
transition: height 0.4s cubic-bezier(0.02, 0.01, 0.47, 1);
overflow: hidden;
height: 0;
padding: 0 10px;
}
.container.open #foldable-content {
height: auto;
/* 注意:height: auto 本身不可过渡 → 需预先设定固定高度或改用 max-height */
}const toggle = document.getElementById('toggle');
const container = document.querySelector('.container');
toggle.addEventListener('click', () => {
container.classList.toggle('open');
});⚠️ 关键注意事项:
#foldable-content {
max-height: 0;
overflow: hidden;
transition: max-heig
ht 0.4s ease-out, padding 0.4s ease-out;
}
.container.open #foldable-content {
max-height: 500px; /* 设为足够容纳全部内容的上限值 */
padding: 10px;
}toggle.addEventListener('click', () => {
const content = document.getElementById('foldable-content');
if (container.classList.contains('open')) {
content.style.height = '0';
// 等过渡结束再设为 none(可选)
setTimeout(() => content.style.display = 'none', 400);
} else {
content.style.display = 'block';
content.style.height = '0';
// 强制重排,触发 height 计算
void content.offsetHeight;
content.style.height = `${content.scrollHeight}px`;
}
container.classList.toggle('open');
});✅ 推荐组合(兼顾简洁与健壮):
最终效果将完全复现 Obsidian Callouts 的流畅体验:点击标题,内容区域以平滑动画展开或收起,无闪烁、无跳变,且兼容响应式布局。