我有以下脚本(在代码段中),当用户向下滚动时会隐藏我的菜单(nav)并在向上滚动时将其恢复。
然而它不起作用,我不确定问题在哪里
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('nav').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('nav').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('nav').removeClass('nav-up').addClass('nav-down');
}}
lastScrollTop = st;
}
.nav-up { top: -100px; }
#s-nav {
position: fixed;
z-index: 999;
top: 0;
width: 100%; height: 100px;
padding-top: 25px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="s-nav" class="nav-down">
<p>navigation</p>
</nav>
答案 0 :(得分:2)
这是因为id is more specify than class:
jQuery(function($) {
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('nav').outerHeight();
$(window).scroll(function(event) {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if (Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > navbarHeight) {
// Scroll Down
$('nav').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('nav').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
});
&#13;
#s-nav.nav-up {
top: -100px;
}
#s-nav {
position: fixed;
top: 0;
width: 100%;
height: 100px;
padding-top: 25px;
transition: top 0.3s;
}
.content {
height: 2000px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="s-nav" class="nav-down">
... nav content ...
</nav>
<div class='content'>
content
</div>
&#13;