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

如何使用jQuery实现div元素缓慢展开与收起的动画效果

问题原因

你使用slide系列方法出现定位异常,核心是这几个常见诱因:

  • jQuery的slide方法执行过程中会临时给元素添加overflow: hidden属性,如果.child_box本身有超出容器的子元素、负margin、未清除的浮动,就会出现布局偏移
  • .child_box如果设置了固定高度/最小高度,或者未开启box-sizing: border-box,动画过程中的高度计算会出错
  • 如果.child_box是绝对定位,父元素未设置position: relative也会导致动画过程中定位漂移

修复方案

方案1:修复jQuery slide动画的定位问题(改动最小)

第一步:先加CSS兼容代码,提前避免定位偏移

.child_box {
  box-sizing: border-box;
  overflow: hidden; /* 提前添加,避免动画过程中jQuery动态赋值时出现跳变 */
  /* 如果你之前给.child_box设置了固定高度,先删除,让高度由内容自然撑开 */
}
/* 如果.child_box的父容器是定位载体,补充下面这句 */
.你的父元素选择器 {
  position: relative;
}

第二步:替换JS逻辑,优化动画执行

把你的JS代码替换为下面的版本,添加了stop()防止多次点击触发动画队列累积,动画时长300ms可自行调整,也可替换为'slow'参数:

$(document).ready(function () {
  const ls = localStorage.getItem('on');
  // 初始化时直接判断显隐,避免首屏出现不必要的动画
  if(ls){
    $(".child_box").show();
  } else {
    $(".child_box").hide();
  }

  $(".open_child").click(function(){
    $(".child_box").stop().slideToggle(300, function(){
      // 动画完成后再操作本地存储,避免状态不同步
      if($(this).is(":hidden")){
        localStorage.clear();
      } else {
        localStorage.setItem('on', true);
      }
    });
  });

  $(".manualclose").click(function(){
    $(".child_box").stop().slideUp(300, function(){
      localStorage.clear();
    });
  });
});

方案2:纯CSS过渡实现(更稳定,无定位异常问题)

如果修改后还是有定位问题,建议用CSS transition实现,可控性更高,不会出现动态改高度导致的布局偏移:

第一步:添加CSS样式

.child_box {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
  box-sizing: border-box;
}
.child_box.active {
  /* 这里的max-height设置为比你的内容最大高度更大的值即可 */
  max-height: 1000px;
}

第二步:替换JS为类名切换逻辑

$(document).ready(function () {
  const ls = localStorage.getItem('on');
  const $childBox = $(".child_box");
  if(ls){
    $childBox.addClass('active');
  }

  $(".open_child").click(function(){
    $childBox.toggleClass('active');
    if($childBox.hasClass('active')){
      localStorage.setItem('on', true);
    } else {
      localStorage.clear();
    }
  });

  $(".manualclose").click(function(){
    $childBox.removeClass('active');
    localStorage.clear();
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:06:06