JQuery动画速度问题

时间:2017-02-09 08:38:51

标签: javascript jquery html css

我想要在滚动时显示div并在用户向后滚动时隐藏,其工作但不是预期的。问题是当我向下滚动然后看起来很好,但是当我向后滚动时,隐藏时会有延迟。

我想要的是显示div从上到下滑动,以及隐藏从下到上的效果。

以下是我一直在尝试的代码:



$(window).scroll(function() {
    var fheader = $(".top-header");
    if ($(this).scrollTop()>50)
     {
        $(fheader).animate({top: "0px"},{duration: 100, easing: "linear"});
     }
    else
     {
      $(fheader).animate({top: "-50px"},{duration: 100, easing: "linear"});
     }
 });

.top-header {
  width: 100%;
  position: fixed;
  height: 50px;
  background: #fff;
  border-bottom: 2px solid #ccc;
  top: -50px;
  left: 0;
}
.content {
  width: 100%;
  height: 1400px;
  float: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="top-header">
   header
</div>
<div class="content">
   this is content
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

只需在stop()之前添加animate,以防止排队:

这是一个有效的例子:

$(window).scroll(function() {
    var fheader = $(".top-header");
    if ($(this).scrollTop()>50)
     {
        $(fheader).stop().animate({top: "0px"},{duration: 100, easing: "linear"});
     }
    else
     {
      $(fheader).stop().animate({top: "-50px"},{duration: 100, easing: "linear"});
     }
 });
.top-header {
  width: 100%;
  position: fixed;
  height: 50px;
  background: #fff;
  border-bottom: 2px solid #ccc;
  top: -50px;
  left: 0;
}
.content {
  width: 100%;
  height: 1400px;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="top-header">
   header
</div>
<div class="content">
   this is content
</div>

相关问题