我想问一下是否有一种方法可以使用 jQuery animate() 方法在窗口滚动时为水平导航栏的顶部属性设置动画。
这是我使用的代码:
window.addEventListener("scroll", function() {
if (window.scrollY > 200) {
$('#navbar').css({top:"100px"});
}
else {
$('#navbar').css({top:"0px"});
}
},false);
CSS:
#navbar{
top:0;
position:fixed;
transition: top 0.5s;
}
当您向下滚动 200 像素时,导航栏将其顶部位置从 0 更改为 100 像素; 这工作正常,但如果我更改方法并使用 .animate 代替 .css,
$('#navbar').animate({top:"100px"});
它停止工作。有什么想法吗?
最佳答案
您可以使用 css transition
来完成此操作,而如何使用 jQuery addClass
而不是 css()
$(window).on('scroll', function () {
if ($(this).scrollTop() > 200) {
if (!$('.navbar').hasClass('expand')) {
$('.navbar').addClass('expand');
}
} else {
if ($('.navbar').hasClass('expand')) {
$('.navbar').removeClass('expand');
}
}
});
.navbar {
top: 0;
position: fixed;
transition: top 0.5s;
}
.navbar.expand {
top: 100px;
}
关于javascript - 如何在窗口滚动时为导航栏设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25951760/