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
Add a ment  | 

2 Answers 2

Reset to default 8

You 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