【问题标题】:Why does adjusting css based on window.scrolltop work consistently while animate does not?为什么基于 window.scrolltop 调整 css 可以始终如一地工作,而 animate 却不能?
【发布时间】:2012-10-08 23:30:39
【问题描述】:

以下内容获取 scrollTop 值并按预期​​调整 css:

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

但以下(更好的效果)没有。当滚动事件完成时,它似乎间歇性地触发

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

有人知道为什么吗?如此简单,但让我精神抖擞。当然我错过了一些东西,非常感谢任何帮助

【问题讨论】:

    标签: jquery css jquery-ui jquery-animate


    【解决方案1】:

    因为滚动事件会在用户移动滚动条时触发很多次,并且每次触发时都会启动一个新动画,因此最终会出现一堆同时运行的动画,它们都试图以不同的方式移动菜单。

    如果你像这样停止之前的动画,它可能会起作用:

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

    但是,如果您在执行动画之前等待滚动操作完成,它可能会更好。请参阅this post 了解等待滚动完成的 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);
        }
    }
    

    【讨论】:

    • 添加了一个新选项,该选项仅在当前动画不是正确的动画目标时才停止,因此,如果它是正确的目标,它将让动画保持平稳运行直到完成,没有抖动。
    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多