一旦用户开始从窗口底部滚动页面,我将尝试删除固定类。下面是我写的代码。但是一旦滚动条到达页面顶部,它就会工作
$(window).scroll(function() {
if ($(this).scrollTop() > 1){
$('.sticky-header').addClass('fixed');
} else{
$('.sticky-header').removeClass('fixed');
}
});
最佳答案
您需要跟踪上一个滚动位置,以便知道滚动方向是向上还是向下。
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>
关于javascript - 如何找到滚动条终点释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54886763/