实现Div高度从0到自适应的平滑切换,仅控制段落显隐
解决方案
问题分析
原代码的核心问题:
- 直接给
<div>设置height:0导致内部固定文本(如"HI")被隐藏 - 使用
display:none会中断过渡动画(display属性不支持过渡) - 高度计算未包含固定内容的高度,导致容器切换时跳动
修正后的代码
HTML
<button class="toggleButton">Toggle 1</button> <div class="container"> HI <p class="paragraph">Paragraph 1.</p> </div> <button class="toggleButton">Toggle 2</button> <div class="container"> Hi <p class="paragraph">Paragraph 2.</p> </div> <button class="toggleButton">Toggle 3</button> <div class="container"> Hi <p class="paragraph">Paragraph 3.</p> </div>
CSS
.container { background: blue; transition: height 0.5s ease; overflow: hidden; } /* 确保固定内容始终可见并排版美观 */ .container > :not(.paragraph) { padding: 8px; margin: 0; } .paragraph { height: 0; opacity: 0; overflow: hidden; transition: height 0.5s ease, opacity 0.5s ease; padding: 0 8px; margin: 0; } .paragraph.visible { opacity: 1; }
JavaScript
const toggleButtons = document.querySelectorAll('.toggleButton'); const containers = document.querySelectorAll('.container'); const paragraphs = document.querySelectorAll('.paragraph'); // 预计算每个容器中固定内容的高度 const fixedContentHeights = Array.from(containers).map(container => { const para = container.querySelector('.paragraph'); const tempDisplay = para.style.display; para.style.display = 'none'; const height = container.offsetHeight; para.style.display = tempDisplay; return height; }); // 初始化容器高度为固定内容高度 containers.forEach((container, index) => { container.style.height = `${fixedContentHeights[index]}px`; }); // 绑定切换事件 toggleButtons.forEach((button, index) => { const container = containers[index]; const paragraph = paragraphs[index]; const fixedHeight = fixedContentHeights[index]; button.addEventListener('click', () => { paragraph.classList.toggle('visible'); if (paragraph.classList.contains('visible')) { // 显示段落:容器高度=固定内容高度+段落真实高度 const paraHeight = paragraph.scrollHeight; paragraph.style.height = `${paraHeight}px`; container.style.height = `${fixedHeight + paraHeight}px`; } else { // 隐藏段落:容器高度=固定内容高度,段落高度归0 paragraph.style.height = '0'; container.style.height = `${fixedHeight}px`; } }); });
关键优化点
- 固定内容始终可见:通过预计算固定内容高度,确保容器始终保留这部分高度,不会隐藏内部的"HI"文本
- 平滑过渡实现:放弃
display:none,改用height+opacity的组合过渡,保证动画连续性 - 精准高度计算:使用
scrollHeight获取段落的真实高度,避免过渡时出现高度偏差 - 类名精准控制:给容器添加
.container类,避免全局样式污染
内容的提问来源于stack exchange,提问作者pichimnc
相关产品推荐
相关产品推荐

