javascript - JQuery 动画速度问题

标签 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>

最佳答案

只需在 animate 之前添加 stop() 即可防止队列执行:

这是一个工作示例:

$(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>

关于javascript - JQuery 动画速度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42131743/

相关文章:

javascript - 从查询sql数据库获取数据到javascript

javascript - 从服务器/主机获取 HTML 代码或显示广告代码

javascript - 查询时并不总是提供参数

Javascript 没有正确扩展类

javascript - 使用转换过滤器根据搜索输入过滤 ng-repeat

javascript - 如果值为零,则更改单元格的样式

html - 元素之间的不稳定间隙

javascript - javascript 中是否有一个行可以使用字符串数组作为对象路径?

javascript - 处理ajax调用后的php错误

javascript - Thymeleaf 页面刷新跟进 - 现在使用 AJAX