带过渡效果的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
相关产品推荐
相关产品推荐

