我正在创建一个1页的网站,我想在用户向下滚动时删除一个类,并在用户向上滚动时添加该类.
我已经做到了这一点,但是它不正确,当用户从顶部向下滚动50px然后该类被移除并且当用户从顶部向上滚动50px时添加它.
我想要它,以便它们几乎可以在页面的底部,如果向上滚动类,如果它们向下滚动,那么它被删除
这是我到目前为止的查询
jQuery(document).ready(function($) {
$(".test").addClass("mobile");
$(window).scroll(function(){
var scroll = $(window).scrollTop();
if (scroll >= 50) {
$(".test").removeClass("mobile");
} else if (scroll <= 50) {
$(".test").addClass("mobile");
}
});
});
Run Code Online (Sandbox Code Playgroud)
因此,这声明了一个全局变量lastScroll来跟踪最后一个已知的滚动位置.用户滚动后,它会将滚动位置与上一个已知滚动位置进行比较,并根据该位置添加或删除您的类.我还删除了<=和> =因为如果滚动位置没有改变(不知何故)我不希望它做任何事情.
var lastScroll = 0;
jQuery(document).ready(function($) {
$(".test").addClass("mobile");
$(window).scroll(function(){
var scroll = $(window).scrollTop();
if (scroll > lastScroll) {
$(".test").removeClass("mobile");
} else if (scroll < lastScroll) {
$(".test").addClass("mobile");
}
lastScroll = scroll;
});
});
Run Code Online (Sandbox Code Playgroud)
根据以下评论,添加以下内容:
var lastScroll = 0;
jQuery(document).ready(function($) {
$(".test").addClass("mobile");
$(window).scroll(function(){
setTimeout(function() { //give them a second to finish scrolling before doing a check
var scroll = $(window).scrollTop();
if (scroll > lastScroll + 30) {
$(".test").removeClass("mobile");
} else if (scroll < lastScroll - 30) {
$(".test").addClass("mobile");
}
lastScroll = scroll;
}, 1000);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4911 次 |
| 最近记录: |