如何找到滚动条终点释放

时间:2019-02-26 13:36:53

标签: javascript jquery html css

我试图在用户开始从窗口底部滚动页面后删除固定的类。以下是我编写的代码。但是,一旦滚动条到达页面顶部,它就会起作用

$(window).scroll(function() {
  if ($(this).scrollTop() > 1){
    $('.sticky-header').addClass('fixed');
  } else{
    $('.sticky-header').removeClass('fixed');
  }
});

1 个答案:

答案 0 :(得分:0)

您需要跟踪上一个滚动位置,以便知道滚动方向是向上还是向下。

var lastScroll = 0;

$(window).scroll(function() {
  var scrollTop = $(this).scrollTop();
  if (scrollTop == 0 || scrollTop < lastScroll) {
    $('.sticky-header').removeClass('fixed');
  } else {
    $('.sticky-header').addClass('fixed');
  }
  lastScroll = scrollTop;
}).triggerHandler('scroll');
.sticky-header {
  min-height: 500vh;
  border: 1em solid #ccc;
}

.sticky-header:before {
  top: 2em;
  left: 2em;
  padding: 1em;
  background: #eee;
  border: 1px solid #999;
  position: fixed;
  content: 'No fixed class';
}

.sticky-header.fixed:before {
  content: 'With fixed class';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div class="sticky-header"></div>