我正在尝试制作一个简单的粘性导航栏,该导航栏在页面顶部不可见,并在向下滚动页面时向下滑动。首先,我使用了scrollUp()/ScrollDown(),但我不喜欢它的外观,因为它对高度进行动画处理,而我想对位置进行动画处理。只是看起来不一样而已。 所以我决定使用 animate() 并将其应用于 margin-top。
HTML:
<div>
...lots of blocks and text
</div>
<div class="top_bar">some elements here</div>
CSS:
.top_bar {
margin-top: -70px;
height:70px;
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 1000;
background:#156373;
color: #fff;
text-align:center;
}
JS:
var stickyBar = function(){
var scroll = $(window).scrollTop();
if (scroll > 100) {
$('.top_bar').animate({
"margin-top": 0
},"fast");
} else {
$('.top_bar').animate({
"margin-top": -70
},"fast");
}
};
$(window).scroll(function() {
stickyBar();
});
问题是它在暂停一段时间后会产生动画。我将页面滚动到最顶部,等待一秒钟,然后顶部栏以动画方式关闭。我向下滚动页面,等待一秒钟,然后 top_bar 开始动画显示。
我不明白这个停顿是从哪里来的...... 请告诉我我做错了什么?
最佳答案
您可能希望使用 CSS3 过渡来获得最灵敏的效果。试试这个:
CSS
.top_bar {
max-height: 0;
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 1000;
background:#156373;
color: #fff;
text-align:center;
transition: all 0.4s cubic-bezier(0, 1, 0.5, 1);
}
.top_bar.sticky {
max-height: 70px;
height: 70px;
}
JS
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.top_bar').addClass("sticky");
} else {
$('.top_bar').removeClass("sticky");
}
});
更新
这里是 jquery animate,没有延迟:
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.top_bar').stop().animate({
"margin-top": 0
}, 200);
} else {
$('.top_bar').stop().animate({
"margin-top": -70
}, 200);
}
});
您只需要确保stop()
之前的动画即可。
关于jQuery animate() 在滚动暂停后触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833402/