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

点击显示列表项内容时,实现超过初始高度的height:auto平滑动画

解决方案:结合透明度与高度的平滑过渡

这问题我太熟了!你需要的就是同时控制内容的透明度和高度变化,既解决未展开时的空白问题,又避免display切换带来的跳跃感。咱们直接调整CSS就能搞定,JS逻辑不用动,具体改法如下:

修改后的完整代码

HTML(保持不变)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<ol class="list-numbers list-numbers--reveal">
 <li><span>Lorem</span></li>
 <li><span>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</span></li>
 <li><span>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</span></li>
 <li><span>Duis aute irure</span></li>
</ol>

CSS(核心修改部分)

.list-numbers { counter-reset: li; line-height: 1.25; list-style: none; }
.list-numbers li { display: flex; min-height: 24px; margin-bottom: 12px; position: relative; text-decoration: none; text-shadow: none; }
.list-numbers li:before { background: black; border-radius: 100%; color: white; content: counter(li); counter-increment: li; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 14px; height: 24px; line-height: 14px; margin-right: 8px; position: relative; top: -2px; width: 24px; }
.list-numbers--reveal li { cursor: pointer; }

/* 核心修改:添加max-height和overflow控制,同时过渡透明度和高度 */
.list-numbers--reveal li span {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
  display: block; /* 确保块级元素,max-height生效 */
  transition: opacity 0.3s ease, max-height 0.3s ease; /* 调整过渡时间让动画更自然 */
}

.list-numbers--reveal li.visible span {
  opacity: 1;
  max-height: 1000px; /* 设置一个远大于内容最大高度的值即可 */
}

JavaScript(保持不变)

$('.list-numbers--reveal li').click(function() { $(this).toggleClass('visible'); });

关键原理说明

  1. 解决空白问题:未展开时span的max-height:0+overflow:hidden,让内容完全隐藏且不占据高度,序号之间不会出现多余空白。
  2. 平滑过渡效果:通过同时过渡opacity(淡入)和max-height(高度展开),实现内容从无到有的平滑出现,下方内容会被自然向下推送,不会有跳跃感。
  3. 保留序号高度:li的min-height:24px刚好匹配序号的高度,未展开时列表项高度和序号一致,布局整齐。

你可以根据自己的需求调整过渡时间(比如把0.3s改成0.2s更快,或者0.4s更慢),max-height的值只要比你最长的内容高度大就不会影响动画效果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:47:39