滚动时隐藏或显示菜单栏



我必须在$('body').scrollTop() > 45时对div进行动画处理

当用户向上滚动时,我需要对相同的div 进行动画处理。我尝试了这段代码,第一个如果有效。如何让第二个条件工作?

    if ($('body').scrollTop() > 45) {
        $('.my-div').animate({
            top:'-45px'
        }, 200);
    }         
    if (¿?user-scrolls-up¿?) {
        $('.my-div').animate({
            top:'0px'
        }, 200);
    } 

一种方法是在滚动时将滚动值保存到变量中。然后,您可以将该值与之前的滚动值进行比较。如果上一个>当前,则用户已向上滚动。

这是这种情况的伪代码

var lastScroll = 0;
$(window).scroll(function() {
    var currentScroll = $(window).scrollTop();
    ... Your first if perhaps using currentScroll ...
    if(currentScroll < lastScroll) {
        $('.my-div').animate({
            top:'0px'
        }, 200);
    }
    lastScroll = currentScroll;
}

或者您可以使用setInterval,将上次迭代间隔的滚动位置与当前迭代进行比较

最新更新