终极解决:JQ jquery 在使用 animate 的时候出现抖动情况,Chrome、IE都会出现这个问题

终极解决:JQ jquery 在使用 animate 的时候出现抖动情况,Chrome、IE都会出现这个问题

啥都不说,先上代码。

  var scrollBool = false;
  var animate_time = 0;
  $(window).scroll(function () {
      if ($(this).scrollTop() >= 200) {
          if (!scrollBool && animate_time == 0) {
              animate_time = 1;//关键:设置为1,防止再次进入动画
              $(".header").stop().animate({
                  "height": "80px"
              }, 200);
              $(".crumbs").stop().animate({
                  "padding-top": "80px"
              }, 200);
              scrollBool = true;
              setTimeout(function () {
                  animate_time = 0;
              }, 210);
          }
      } else {
          if (scrollBool && animate_time == 0) {
              animate_time = 1;//关键:设置为1,防止再次进入动画
              $(".header").stop().animate({
                  "height": "120px"
              }, 200);
              $(".crumbs").stop().animate({
                  "padding-top": "120px"
              }, 200);
              scrollBool = false;
              setTimeout(function () {
                  animate_time = 0;
              }, 210);
          }
      }

  });

以上代码就是在鼠标滚动时,收起菜单、展开菜单的动画。原来会有抖动的情况,加了stop(),仍然没有用。
 $(".crumbs").stop().animate();//没有卵用

分析不就是动画还没结束前,又触发新的动画,导致的不停在动画过程之中,于是就想到了两个方法。

1、在animate的回调方法中再调用第二个动画。(selector).animate({styles},speed,easing,callback) //有效果但不能完全解决。

2、直接使用setTimeout,这个时间略大于动画的时间,这个保证这个动画没结束前,绝对不会出现再次进入的情况。

------------------------------------------

划重点 --- 关键代码如下:

var animate_time = 0;//为0时才允许动画
if(animate_time == 0){
      animate_time = 1;
      $(".header").stop().animate({"height":"80px"},200);
      $(".crumbs").stop().animate({"padding-top":"80px"},200);
      setTimeout(function(){animate_time = 0;},210);//动画时间是200ms, 210ms后才允许再次运行动画
}

这个方法亲试能彻底解决 jquery 在使用 animate 的时候出现抖动情况,Chrome下测试完全没问题,哈哈!!!!

猜你喜欢

转载自blog.csdn.net/cen_cs/article/details/79018061