Add Class only on browser Scroll Up

2019-09-11 02:19发布

There any way to add class only when Scroll Up browser page.

Problem Filide>>

JS

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll <= 100) {
        $(".nav").addClass("darkHeader");
    } else {
        $(".nav").removeClass("darkHeader");
    }
});

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

1条回答
甜甜的少女心
2楼-- · 2019-09-11 02:48

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;
});

JSFiddle

查看更多
登录 后发表回答