为什么我的 Jquery "animate"只触发一次,而不是每次触发函数?



我正在以特定的文档高度停靠到视口顶部的导航,当它停靠时,它具有下拉动画。

  $(document).scroll(function(){
    var x = $(window).scrollTop();
    if(x>=700){
      $("header").addClass("fix");
      if($("header").hasClass("fix")){
        $("header").animate({top: '0'},500);
      }
      $("main").css("padding-top", "100px");
    }
    if(x<=300){
      if($("header").hasClass("fix")){
            $("main").removeAttr("style");
            $("header").removeClass("fix");
      }}
  });
header{background:green}
main{height:2000px;background:yellow;}
#header{padding:20px; display: inline-flex;}
.fix{
  width:100%;
  position:fixed;
  top:-100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div id="header">
<a href="http://stackoverflow.com">Stack overflow</a>
</div>
</header>
<main>
</main>

我的问题是,在滚动回到页面顶部并再次向下滚动页面后,导航弹出。它不会下降(显示动画(,我该如何修复?

https://jsfiddle.net/damiantoczek/rc05odu8/

(我自己写了该代码,而不是复制糊(

您可以使用普通CSS进行操作:

header {  
  top: -100px;
  transition: top .5s;
}
header.fix{
  width:100%;
  position:fixed; 
  top: 0;
}

只需从JS

中删除animate调用

编辑:这是小提琴

作为 @sklingler93使用CSS过渡的答案似乎是最好的方法,OP的答案是:

  1. 当滚动事件触发了很多次功能时,您应该在.animate(...)之前使用.stop(),以确保不排队动画。
  2. 您忘了在if <300语句中删除标头的样式属性。

这是您的代码的答案,因为有一些没有用的说明:https://jsfiddle.net/rc05odu8/2/

或仅修复您的代码:

  $(document).scroll(function() {
    var x = $(window).scrollTop();
    if (x >= 700) {
      $("header").addClass("fix");
      $("header").stop().animate({
        top: '0'
      }, 500);
      $("main").css("padding-top", "100px");
    }
    if (x <= 300) {
      $("main").removeAttr("style");
      $('header').removeAttr('style');
      $("header").removeClass("fix");
    }
  });

我认为在这个片段...

if(x>=(a-100)){
  $("header").addClass("fix");
  if($("header").hasClass("fix")){
    $("header").animate({top: '0'},500);
  }
  $("main").css("padding-top", "100px");
}
  1. $("header").addClass("fix");应该在if($("header").hasClass("fix"));
  2. 可能$("main").css("padding-top", "100px");也应该在if内;
  3. 您应该否定if表达式;

这样,您将拥有:

if(x>=(a-100))
{
  if(!$("header").hasClass("fix"))
  {
    $("header").addClass("fix");
    $("header").animate({top: '0'},500);
    $("main").css("padding-top", "100px");
  }
}

对我来说更有意义。

另外,您必须清除所有当滚动返回顶部时,动画应用的样式。

希望它有帮助。

最新更新