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

时间:2015-07-09 23:38:12

标签: javascript jquery html css sticky

我制作了这个片段代码来隐藏菜单向下滚动并显示向上滚动但我有一些问题,当我滚动到顶部菜单仍然有固定的位置,我怎么能解决这个问题,谢谢!
JAVSCRIPT:

$(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

4 个答案:

答案 0 :(得分:3)

对于第一个侦听器,只需添加一个else语句,如下所示:

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

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

另请注意,第二位听众不需要setInterval(),请参阅jsfiddle

答案 1 :(得分:1)

我测试了它,而且效果很好!

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

答案 2 :(得分:0)

使用removeClass为你的scrollTop添加一个else,你应该没事,我测试了它并且它有效。这里

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

答案 3 :(得分:0)

使用变量检测导航方向

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过渡进行平滑的显示/隐藏

.mainmenu {
    transition:all 0.5s ;
}