Add Class only on browser Scroll Up

青春壹個敷衍的年華 提交于 2019-12-12 01:22:00

问题


Is there any way to add class to an element only when someone scrolls the browser page up?

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



来源:https://stackoverflow.com/questions/30559819/add-class-only-on-browser-scroll-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!