You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带过渡效果的CSS展开折叠Div:max-height替代none的实现方案

适配超长文本的Div展开/折叠完美实现方案

核心问题在于CSS过渡需要具体的数值触发动画,max-height: none无法触发过渡。解决思路是用JavaScript获取元素的真实内容高度,动态赋值给max-height,兼顾过渡效果和超长文本适配。

修改后的CSS代码

.smalldesc {
  max-height: 52px;
  overflow: hidden;
  transition: max-height 1s ease; /* 仅过渡max-height,提升性能 */
  border: 1px solid red;
}

配套JavaScript实现

// 获取操作元素
const toggleButton = document.querySelector('.toggle-btn');
const descBox = document.querySelector('.smalldesc');
// 缓存初始折叠状态的max-height值
const collapsedHeight = getComputedStyle(descBox).maxHeight;

toggleButton.addEventListener('click', () => {
  const isExpanded = descBox.classList.contains('expand');

  if (isExpanded) {
    // 折叠:恢复初始max-height
    descBox.style.maxHeight = collapsedHeight;
    descBox.classList.remove('expand');
    toggleButton.textContent = '展开';
  } else {
    // 展开:获取元素真实内容高度并设置
    const fullHeight = descBox.scrollHeight + 'px';
    descBox.style.maxHeight = fullHeight;
    descBox.classList.add('expand');
    toggleButton.textContent = '折叠';
  }
});

关键细节说明

  • scrollHeight:获取元素包含所有内容的真实高度(包括超出隐藏的部分),完美适配任意长度文本
  • 仅过渡max-height:避免过渡不必要的属性,优化动画性能
  • 缓存初始高度:用getComputedStyle读取CSS中定义的折叠高度,避免硬编码数值,提升代码灵活性
  • 动态切换逻辑:通过类名标记展开状态,结合内联样式设置具体高度,保证过渡动画正常触发

如果遇到内容动态更新的场景(比如异步加载文本),可以在展开前重新计算scrollHeight,确保高度始终准确。

内容的提问来源于stack exchange,提问作者Haradzieniec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:00:06