Header 滚动消失

Header disappearing on scroll

我试图让我的 header 在向下滚动时消失,而在向上滚动时只 re-appear。我无法让它工作: http://jsfiddle.net/mxj562qt/

有什么地方出错了吗?

HTML:

<div id="header" class="custom-header">
    This is your menu.
</div>
<main>
    This is your body.
</main>
<footer>
    This is your footer.
</footer>

Javascript:

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

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

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

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
        $("#header").addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $("#header").removeClass('nav-up');
        }
    }
    
    lastScrollTop = st;
}

CSS:

body {
    padding-top: 40px;
}

#header {
    background: #f5b335;
    height: 50px;
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}

.nav-up {
    top: -50px;
}

main {
    height: 2000px;
}

footer { background: #ddd;}
* { color: transparent}

CSS class 似乎没有被添加,但我不确定为什么。我是否以错误的方式引用了 Div?

问题出在您的 CSS 上。您在代码中指定了 position:fixed; 并且 CSS 的那一点会覆盖您正在编写的所有 JS。固定将强制您的 header 可见,无论您在做什么。相反,您可以在 CSS:

中试试这个
body {
    padding-top: 40px;
}

#header {
    background: #f5b335;
    height: 50px;
    position: absolute;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}

.nav-up {
    top: -50px;
}

main {
    height: 2000px;
}

footer { background: #ddd;}
* { color: transparent}

absolute 属性 应该使它在滚动时消失。而且,您对 <div> 标签的引用没有错!

所以,我可以看出问题源于这段代码...

// Scroll Up
if(st + $(window).height() < $(document).height()) {
    $("#header").removeClass('nav-up');
}

在我的测试中,doc 高度总是大于 st + window 高度。

我这样做了...

// Scroll Up
console.log('doc height: ', $(document).height());
console.log('st+window height: ', st + $(window).height());
        
if(st + $(window).height() < $(document).height()) {
    $("#header").removeClass('nav-up');
}

// results from scrolling up + down
// doc height:       2058
// st+window height: 313
// doc height:       2058
// st+window height: 280
// doc height:       2058
// st+window height  1614
// doc height:       2058
// st+window height: 1580

将前面提到的 JS 更改为这个似乎可以让您到达所需的位置。

$("#header").removeClass('nav-up');

然后你的 CSS 需要一些工作......

我注意到由于 CSS 选择器优先级,您的 top 元素没有应用。

.nav-up {
    top: -50px !important;
}

结果:向下滚动,导航栏隐藏,向上滚动,导航栏显示。

我在下面分叉了你的代码; http://jsfiddle.net/itsbjk/aw6qb2mr/16/