Jquery 为什么基于window.scrolltop调整css会一直有效,而动画则不会?

Jquery 为什么基于window.scrolltop调整css会一直有效,而动画则不会?,jquery,css,jquery-ui,jquery-animate,Jquery,Css,Jquery Ui,Jquery Animate,以下内容选择scrollTop值并按预期调整css: $(window).scroll(function() { if($window.scrollTop()>918){ $menu.css({top:'0px'}); } else{ $menu.css({top:'80px'}); } } 但是下面的(更好的效果)没有。当scroll事件完成时,它似乎会间歇性地激发

以下内容选择scrollTop值并按预期调整css:

      $(window).scroll(function() {
      if($window.scrollTop()>918){
        $menu.css({top:'0px'});
        }
      else{
        $menu.css({top:'80px'});
        }
      }
但是下面的(更好的效果)没有。当scroll事件完成时,它似乎会间歇性地激发

       $(window).scroll(function() {
       if($window.scrollTop()>918){
        $menu.animate({top:'0px'},100);
        }
      else{
        $menu.animate({top:'80px'},100);
        }
        }

有人知道为什么吗?这么简单,却让我精神崩溃。当然,我遗漏了一些东西,非常感谢您的帮助,因为当用户移动滚动条时,滚动事件会多次触发,每次触发时,您都会启动一个新的动画,因此最终会出现一组同时运行的动画,这些动画都试图以不同的方式移动菜单

如果按以下方式停止上一个动画,则可能会起作用:

$(window).scroll(function() {
    if($window.scrollTop()>918){
        $menu.stop(true).animate({top:'0px'},100);
    } else {
        $menu.stop(true).animate({top:'80px'},100);
    }
}
但是,如果在制作动画之前等待滚动操作完成,效果可能会更好。有关等待滚动完成的jQuery加载项方法,请参阅


编辑:我有一个更好的主意。在第一次滚动移动时启动动画,并允许其继续运行,除非值发生更改:

$(window).scroll(function() {
    var menuTarget = $window.scrollTop()>918 ? "0px": "80px";
    // only do an animation if one isn't already going or
    // the current animation target is not what we want
    if (!$menu.is(":animated") || $menu.data("animTarget") !== menuTarget) {
        // set the new target, stop the current animation and start new animation
        $menu.data("animTarget", menuTarget)
            .stop(true).animate({top: menuTarget},100);
    }
}

因为滚动事件会在用户移动滚动条时多次触发,每次触发时,您都会启动一个新动画,因此最终会出现一组同时运行的动画,这些动画都试图以不同的方式移动菜单

如果按以下方式停止上一个动画,则可能会起作用:

$(window).scroll(function() {
    if($window.scrollTop()>918){
        $menu.stop(true).animate({top:'0px'},100);
    } else {
        $menu.stop(true).animate({top:'80px'},100);
    }
}
但是,如果在制作动画之前等待滚动操作完成,效果可能会更好。有关等待滚动完成的jQuery加载项方法,请参阅


编辑:我有一个更好的主意。在第一次滚动移动时启动动画,并允许其继续运行,除非值发生更改:

$(window).scroll(function() {
    var menuTarget = $window.scrollTop()>918 ? "0px": "80px";
    // only do an animation if one isn't already going or
    // the current animation target is not what we want
    if (!$menu.is(":animated") || $menu.data("animTarget") !== menuTarget) {
        // set the new target, stop the current animation and start new animation
        $menu.data("animTarget", menuTarget)
            .stop(true).animate({top: menuTarget},100);
    }
}

添加了一个新选项,该选项仅在当前动画不是正确的动画目标时停止当前动画,因此,如果它是正确的目标,它将使动画保持平稳运行直至完成,而不会出现抖动。添加了一个新选项,该选项仅在当前动画不是正确的动画目标时停止当前动画,因此如果它是正确的目标,它将使动画一直平稳地运行到完成,而不会出现抖动。