我正在尝试实现 navbar
在从页面底部滚动到顶部时固定。当我们从顶部滚动到底部时,位置必须是相对的。
I want to add the class when I scroll back to menu from bottom and remove it at the end reaching the menu again.
我试过使用负值的 scrollTop
但它对我不起作用。
提前致谢!
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('nav').addClass("sticky");
} else {
$('nav').removeClass("sticky");
}
});
$(window).scroll(function() {
if ($(this).scrollTop() > -200) {
$('nav').addClass("sticky");
} else {
$('nav').removeClass("sticky");
}
});
* {
box-sizing: border-box;
}
nav {
height: 70px;
background: #f00;
position:relative;
}
nav.sticky {
-webkit-transition: all 300ms ease-in 0s;
transition: all 300ms ease-in 0s;
left: 0;
position: fixed;
right: 0;
top: 0;
z-index: 1049;
}
section {
height: 900px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav></nav>
<section></section>
最佳答案
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
$('nav').removeClass("sticky");
} else {
$('nav').addClass("sticky");
}
lastScrollTop = st;
});
* {
box-sizing: border-box;
}
nav {
height: 70px;
background: #f00;
position:relative;
}
nav.sticky {
-webkit-transition: all 300ms ease-in 0s;
transition: all 300ms ease-in 0s;
left: 0;
position: fixed;
right: 0;
top: 0;
z-index: 1049;
}
section {
height: 900px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav></nav>
<section></section>
您必须保存您的 ScrollTop 值并进行比较!
关于javascript - jQuery 滚动到底部 addClass 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56055270/