奇怪的jQuery动画行为-不断重复运行

时间:2019-05-14 15:51:07

标签: css jquery-animate

问题 我正在从左到右动画一些文本。它应该只运行一次并在可见时完成(除非在可见时才运行!),但是由于某种原因,尽管它正确地等待它在可见,但它不断地循环,缓慢推动元素离开页面。

如果您对我如何停止这种怪异有任何见解,我将不胜感激!

这是该网站的一个示例,如果觉得有用,也可以看到它。

https://stable.stable-demos.com/who-we-are/

jQuery(function($){
  $(window).scroll(function () {
    var y = $(window).scrollTop(),
      x = $('.div6').offset().top - 100;
      if (y > x) {
         $('.div6').delay(1300).animate({ opacity: 1, "margin-left": '+=50'});
      } else {
        // do not run the animation
      }
  });
 });
.div6 {
  opacity: 0;
  font-size: 48px;
  margin-left: -50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div6">
		<div class="wrapper">
			<h2>At The Stable, we are for you. We tackle your problems for you and celebrate your victories with you.</h2>
		</div>
	</div>

1 个答案:

答案 0 :(得分:1)

您需要跟踪动画是否已触发,然后不要让其触发。可以通过如下所示的变量来完成:

var done = false;
jQuery(function($) {
  $(window).scroll(function() {
    if (!done) {
      var y = $(window).scrollTop(),
        x = $('.div6').offset().top - 100;
      if (y > x) {
        done = true;
        $('.div6')
          .delay(1300)
          .animate({
            opacity: 1,
            marginLeft: '+=50'
          });
      }
    }

  });
});
.div6 {
  opacity: 0;
  font-size: 48px;
  margin-left: -50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div6">
  <div class="wrapper">
    <h2>At The Stable, we are for you. We tackle your problems for you and celebrate your victories with you.</h2>
  </div>
</div>