向下滚动时隐藏菜单,向上滚动时显示

Hide menu on scroll down and show on scroll up

我制作了这段代码来在向下滚动时隐藏菜单并在向上滚动时显示但是我有一些问题,当我滚动到顶部时菜单仍然有固定的位置,我该如何解决这个问题,谢谢!
脚本:

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > 500) {
        $('.mainmenu').addClass('nav-down');
    }
});

// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.mainmenu').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 500);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('.mainmenu').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('.mainmenu').removeClass('nav-up');
        }
    }

    lastScrollTop = st;
}

CSS :

.mainmenu {
    background: #222;
    height: 50px;
    padding: 0 15px;
    width: 80%;
    margin: 0 auto;
}
.nav-down{
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}
.nav-up {
    top: -50px;
}

演示:jsfiddle

使用 removeClass 将 else 添加到您的 scrollTop,您应该没问题,我测试了它并且它有效。这里

$(window).bind('scroll', function () {
if ($(window).scrollTop() > 500) {
    $('.mainmenu').addClass('nav-down');
}
else
{
    $('.mainmenu').removeClass('nav-down');
}
});

给你第一个听众,只需添加一个else语句如下:

$(window).bind('scroll', function () {

    if ($(window).scrollTop() > 150)
        $('.mainmenu').addClass('nav-down');
    else
        $('.mainmenu').removeClass('nav-down');
});

另请注意,第二个侦听器不需要 setInterval(),请参阅 jsfiddle

用变量检测导航方向

var lastscrolltop=0;
jQuery(window).bind('scroll', function () {
        if (jQuery(window).scrollTop() > lastscrolltop)
            jQuery('.mainmenu').addClass('nav-up');
        else
            jQuery('.mainmenu').removeClass('nav-up');
        lastscrolltop=jQuery(window).scrollTop();
});

并使用 css 平滑过渡 show/hide

.mainmenu {
    transition:all 0.5s ;
}

我测试了它,它工作正常!!

$(window).bind('scroll', function () {
if ($(window).scrollTop() > 500) {
    $('.mainmenu').addClass('nav-down');
}
else
{
    $('.mainmenu').removeClass('nav-down');
}
});