简体   繁体   中英

Why does my jquery take so long when animating on scroll?

I have a box that slides right 100px when you scroll 10px and slide back to it's default location if the scroll is less than 10px. The box does animate, however, there is a bit of a delay when it does. Can anyone help me figure this out?

HTML

<div id="nest">
  <div id="box">

  </div>
</div>

CSS

#nest {
  width: 95%;
  max-width: 1000px;
  margin: auto;
  background-color: orange;
  height: 1000px;
  padding-top: 150px
}

#box {
  margin: 50px 0px 0px 0px;
  width: 100px;
  height: 100px;
  position:relative;
  background-color: green;
}

jQuery

jQuery(window).scroll(function() {
  if (jQuery(this).scrollTop() > 10) {
    jQuery('#box').animate({left:'100px'})


  } else {
    jQuery('#box').animate({left:'0px'})
}
});

My JSFIDDLE LINK https://jsfiddle.net/ispykenny/m6ffj83g/1/

thanks in advance for your time and help!

The reason your animation is taking so long would be that the animate is running on every scroll event past 10px, and this is quite intensive on the client-side. There are a few options, either experiment with the .stop() functionality in jQuery, or write aa conditional if statement that checks if the animation will have started and only fires if it hasn't.

https://api.jquery.com/stop/

this is a handy resource.

var coin = false;

jQuery(window).scroll(function() {
  if (jQuery(this).scrollTop() > 10 && coin === false) {
    jQuery('#box').animate({left:'100px'});
    coin = true;
  } else if (coin === true && jQuery(this).scrollTop() <= 10) {
    jQuery('#box').animate({left:'0px'});
    coin = false;
}
});

try this!

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