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

如何实现Checkbox控制的元素高度自适应平滑动画?

解决Checkbox控制自适应高度元素的平滑过渡动画问题

CSS的transition无法直接对height: auto进行过渡,因为浏览器无法计算auto到0的中间值,这就是移除固定高度后动画失效、直接跳变的原因。我们可以通过JS动态获取元素的实际内容高度,配合CSS过渡实现自适应高度的平滑动画。

修改后的实现代码

HTML(无需改动)

<div class="container py-4">
  <form id="contactForm">
    <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" value="1" id="attendance">
      <label class="form-check-label" for="flexCheckDefault">I will be attending</label>
    </div>
    <div class="info-container hidden mb-4">
      <div class="mb-3">
        <label class="form-label" for="emailAddress">Email Address</label>
        <input class="form-control" id="emailAddress" type="email" placeholder="Email Address" />
      </div>
      <div class="mb-3">
        <label class="form-label" for="message">Comment</label>
        <textarea class="form-control" id="message" type="text" placeholder="Comment" style="height: 10rem;"></textarea>
      </div>
    </div>
    <div class="d-grid">
      <button class="btn btn-primary btn-lg" type="submit">Submit</button>
    </div>
  </form>
</div>

CSS(调整过渡逻辑,添加溢出控制)

.info-container {
  opacity: 1;
  overflow: hidden; /* 隐藏过渡过程中溢出的内容 */
  transition: all 500ms ease;
}

.hidden {
  opacity: 0;
  height: 0;
}

JS(动态计算高度,实现平滑过渡)

const infoContainer = $('.info-container');
const attendanceCheckbox = $('#attendance');

// 监听复选框点击事件
attendanceCheckbox.on('click', function() {
  if ($(this).is(':checked')) {
    // 显示元素:先移除hidden类,获取实际高度后设置
    infoContainer.removeClass('hidden');
    // 强制浏览器重绘,确保能获取到正确的scrollHeight
    void infoContainer[0].offsetHeight;
    const naturalHeight = infoContainer[0].scrollHeight;
    infoContainer.css('height', naturalHeight + 'px');
    
    // 动画结束后,将height设为auto,支持内容自适应
    infoContainer.one('transitionend', function() {
      infoContainer.css('height', 'auto');
    });
  } else {
    // 隐藏元素:先设置为当前实际高度,再触发过渡到0
    const currentHeight = infoContainer[0].scrollHeight;
    infoContainer.css('height', currentHeight + 'px');
    // 强制重绘后添加hidden类
    void infoContainer[0].offsetHeight;
    infoContainer.addClass('hidden');
    
    // 动画结束后清除内联height样式
    infoContainer.one('transitionend', function() {
      infoContainer.css('height', '');
    });
  }
});

原理说明

  1. 获取真实高度:使用scrollHeight获取元素内容的完整高度,包含所有溢出的内容部分。
  2. 强制重绘触发:void element.offsetHeight强制浏览器完成重绘,确保获取到的高度是最新的元素尺寸,避免过渡逻辑失效。
  3. 恢复自适应能力:显示动画结束后将height设为auto,保证元素内容变化时能自动调整高度;隐藏动画结束后清除内联样式,避免影响下次显示逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:55:22