仅在浏览器上添加课程向上滚动 [英] Add Class only on browser Scroll Up

查看:111
本文介绍了仅在浏览器上添加课程向上滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有当有人向上滚动浏览器页面时,才可以将类添加到元素吗?

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

JSFiddle

这篇关于仅在浏览器上添加课程向上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆