简体   繁体   中英

Reversing the changes on CSS caused by the animation effect using jquery.animate() and jquery.scroll()

Is there a way to reverse the CSS changes caused by jQuery.animate() according to the position of the scroll ? I am working on a website where I want a certain animation effect to occur on an element when a user scrolls down. After that when the user scrolls up the element must get back to its previous state. an example:

$(window).scroll(function(){
    if(this.scrollTop() >= 300){  //Scrolling down to a point 300 or more
        $('.foo').animate({
            'width': 100 
           'height': 100 
        }, 500, 'swing');     
     }
});

As you can see from the above snippet, the effect happens when the user scrolls down. Now below is a code which I can logically think of as to how the reverse effect will work:

if(this.scrollTop() <= 300) {  //Scrolling down to a point 300 or more    
    $('.foo').animate({
        'width': 10 
        'height': 10
    }, 500, 'swing');     
 }

Click THE FIDDLE to see the code in action and get a better insight.

I have seen a lot of plugins doing this however, Is there a better way of doing the above mentioned scenario using just jQuery.animate() binded by the jQuery.scroll() ? If so, Could you please show me an example ? or could you direct me to a link ? Please guide me/advice me.

Thanks for your help !

If you don't need to force jquery to edit the CSS of the object, you could tell it to add/remove classes instead which will give you a similar effect.

If your object's style is already composed as 10px width/height, then you can have a style like

.bar{
   height: 100px;
   width: 100px;
}

and in your javascript code:

if(this.scrollTop() >= 300){
    this.addClass('bar');
}

then you can just do

removeClass('bar'); 

when you don't need it.

https://api.jquery.com/addclass/

https://api.jquery.com/removeclass/

You can use a class for that, create a class with the properties you want, in your case

.scrolled {
  height: 100px;
  width: 100px;
}

Then addClass, it accepts the other options you wanted, so you can

if(this.scrollTop() >= 300){
    this.addClass('scrolled', 500, 'swing');
}

if(this.scrollTop() < 300){
    this.removeClass('scrolled', 500, 'swing);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM