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

实现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`;
    }
  });
});

关键优化点

  1. 固定内容始终可见:通过预计算固定内容高度,确保容器始终保留这部分高度,不会隐藏内部的"HI"文本
  2. 平滑过渡实现:放弃display:none,改用height+opacity的组合过渡,保证动画连续性
  3. 精准高度计算:使用scrollHeight获取段落的真实高度,避免过渡时出现高度偏差
  4. 类名精准控制:给容器添加.container类,避免全局样式污染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:33:25