问题描述:

i have this menu that i only want to show if the user scrolls the site up or when no scrolling happens. So when the site is scrolled up or no scroll happens i want to show it. when scroll down i want to hide it.

My current code is:

 var lastScrollTop = 0;

$(window).on("scroll touchmove", function () {

var st = $(this).scrollTop();

if (st > lastScrollTop){

$('.mobile-nav').css('top',-65);

} else {

$('.mobile-nav').css('top',0);

}

lastScrollTop = st;

$('.mobile-nav').toggleClass('tiny', $(document).scrollTop() > 0);

});

网友答案:

Try this...

var lastScrollTop = 0;
var timeoutID = 0;
$(window).on("scroll touchmove", function () {
    var st = $(this).scrollTop();
    if (st > lastScrollTop){
        $('.mobile-nav').css('top',-65);
        clearTimeout(timeoutID);
        timeoutID = setTimeout(function() {
            $('.mobile-nav').css('top',0);
        }, 500);
    } else {
        $('.mobile-nav').css('top',0);
    }
    lastScrollTop = st;
    $('.mobile-nav').toggleClass('tiny', $(document).scrollTop() > 0);
});

I've added a timer to show the menu again when you stop scrolling, which is the only eventuality your code didn't cover.

Whenever you scroll down it will start a 0.5 second timer that will show the menu again. If you continue scrolling then that timer is destroyed and a new one is created, starting the 0.5 second check all over again. Obviously change the 500 to suit your taste :)

网友答案:

The same can be done with hidden class and fixed positioning:

var lastScrollTop = 0,
    show = function () {
        $('.mobile-nav').removeClass('hidden');
    },
    timeOut = setTimeout(show, 1000);
$(window).on("scroll touchmove", function () {
    clearTimeout(timeOut);
    var st = $(this).scrollTop();
    if (st > lastScrollTop) {
        $('.mobile-nav').addClass('hidden');
    } else {
        $('.mobile-nav').removeClass('hidden');
    }
    lastScrollTop = st;
    timeOut = setTimeout(show, 1000);
    //$('.mobile-nav').toggleClass('tiny', $(document).scrollTop() > 0);
});

The second argument in setTimeout is for milliseconds of being "idle" - you can move it to a separate variable to make code more clear.

Working fiddle: http://jsfiddle.net/neustroev_ai/L8y2cwyz/

相关阅读:
Top