仅在浏览器上添加课程向上滚动
问题描述:
只有当有人向上滚动浏览器页面时,才可以将类添加到元素吗?
Is there any way to add class to an element only when someone scrolls the browser page up?
问题 Filide >>
JS
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll <= 100) {
$(".nav").addClass("darkHeader");
} else {
$(".nav").removeClass("darkHeader");
}
});
问题是此js向下滚动页面时添加的类.但是我想在向上滚动浏览器时添加类,然后在向下滚动浏览器时删除类.
请参见示例
Problem is this js add class when scroll-down page. But I want to add class when Scroll Up browser and after that when scroll down class will remove.
See Example demo>>
答
如果您想知道用户是向上滚动还是向下滚动,则需要跟踪最后一个滚动位置.然后检查新滚动位置是否大于或小于该位置.然后,您可以相应地设置类
If you want to know whether the user has scrolled up or down you need to track of the last scroll position. Then check if the new scroll position is greater or less than that position. You can then set the classes accordingly
// Script
lastScroll = 0;
$(window).on('scroll',function() {
var scroll = $(window).scrollTop();
if(lastScroll - scroll > 0) {
$(".nav").addClass("darkHeader");
} else {
$(".nav").removeClass("darkHeader");
}
lastScroll = scroll;
});