我試圖讓我的標題在向下滾動時消失,并且只在向上滾動時重新出現。我無法讓它作業: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 類,但我不確定為什么。我以錯誤的方式參考 Div 嗎?
uj5u.com熱心網友回復:
所以,我可以看到問題源于這段代碼......
// Scroll Up
if(st $(window).height() < $(document).height()) {
$("#header").removeClass('nav-up');
}
在我的測驗中,檔案高度總是 > 大于 st 視窗高度。
我做了這個...
// 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需要一些作業......
我注意到top由于 CSS 選擇器優先級,您的元素沒有應用。
.nav-up {
top: -50px !important;
}
結果:向下滾動,導航欄隱藏,向上滾動,導航欄顯示。
我在下面分叉了你的代碼; http://jsfiddle.net/itsbjk/aw6qb2mr/16/
uj5u.com熱心網友回復:
這里的問題在于您的 CSS。您已position:fixed;在代碼中指定,并且那一點 CSS 會覆寫您正在撰寫的所有 JS。無論您在做什么,已修復都會強制您的標題可見。相反,你可以在你的 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>標簽的參考沒有錯!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/470276.html
標籤:javascript html jQuery css
下一篇:雙擊任何單元格將被洗掉
