admin管理员组文章数量:1293651
I'd like to ask if there is a way to use jQuery animate() method to animate horizontal navbar's top property on window scroll.
Here is code I use:
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;
}
When you scroll down 200px the navbar changes its top position from 0 to 100px; This works fine, but if I change methods and put .animate instead of .css,
$('#navbar').animate({top:"100px"});
it stops working. Any ideas why?
I'd like to ask if there is a way to use jQuery animate() method to animate horizontal navbar's top property on window scroll.
Here is code I use:
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;
}
When you scroll down 200px the navbar changes its top position from 0 to 100px; This works fine, but if I change methods and put .animate instead of .css,
$('#navbar').animate({top:"100px"});
it stops working. Any ideas why?
Share Improve this question edited Sep 20, 2014 at 18:27 Florin Pop 5,1354 gold badges28 silver badges60 bronze badges asked Sep 20, 2014 at 18:02 TomasRTomasR 453 silver badges5 bronze badges 2- This can be achieved by using CSS3 transitions. stackoverflow./questions/20185001/… – Harshadewa Commented Sep 20, 2014 at 18:44
- Please see the updated my second link. – Modder Commented Sep 20, 2014 at 18:57
2 Answers
Reset to default 8You can do this with css transition
and how you can achieve this is with jQuery addClass
instead of css()
DEMO
$(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;
}
Scroll event listener execute every time when you scroll page on every pixel, and animate starts from begin. This gives unexpected results.
http://jsfiddle/29tkxawy/
You should be leave as is (with .css()
).
Or like this without css transition:
http://jsfiddle/29tkxawy/10/
本文标签: javascripthow to animate navbar on window scrollStack Overflow
版权声明:本文标题:javascript - how to animate navbar on window scroll - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741582503a2386650.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论