Add Class only on browser Scroll Up

2019-09-11 02:10发布

问题:

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:

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