简体   繁体   中英

smoothest way to change jquery.animate mid-animation

I am animating an element on the screen using jQuery.animate in response to the window scroll event like this:

$(window).scroll(function(){
  $("#myElement").stop().animate({top: -0.5 * $(window).scrollTop()});
});

Since the scroll event fires over and over when you're scrolling a window, I have to call the.stop() function on my element in order to immediately start my next animation.

This seems to work okay, but can be a bit slow when there's a lot of content being animated. Is there a better way to update the target values of an animation mid-animation? What can I do to improve the performance of this code?

Have you ever thought of just doing a more specific .css change?

$(window).scroll(function(){
  $("#myElement").css({top: -0.02 * $(window).scrollTop()});
});

I just put in an arbitrary number, but it might be worth trying and playing with. It should be smoother if you figure out the right modifiers.

Also: It'd be nice if you accepted a few more answers. You have only accepted 31% of the questions you've asked. Just a thought.

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