动画(绑定到 scrollTop)仅在我停止滚动时结束

Animation (bound to scrollTop) only finishes when I stop scrolling

当滚动达到 15% 以上时,我的动画事件几乎暂停或者说完成速度明显变慢。这是为什么?如果应该向左动画,但只有当我停止滚动时它才会这样做。

$(window).scroll(function ()
{
    var content_height = $(document).height();
    var content_scroll_pos = $(window).scrollTop();
    var percentage_value = content_scroll_pos * 100 / content_height;

    if(percentage_value > 15)
    {
    TweenMax.to(".bar", 3, {right:"0", ease:Bounce.easeOut})

    }
     else
    {
            TweenMax.to(".bar", 2, {right:"-125%", ease:Power2.easeOut})

    }
});

这里有一个带有解释注释的解决方案演示:

// This gets called _every time_, you scroll a little bit ("every time" as in "every frame").
// So we introduce a new variable that acts as a filter and only lets the function trigger, once the status changes.
// 0 = not changed (it is, where it was on page loading)
// 1 = out of the screen
// 2 = back in the screen
var status = 0;
$(window).scroll(function ()
{
  var content_height = $(document).height();
  var content_scroll_pos = $(window).scrollTop();
  var percentage_value = content_scroll_pos * 100 / content_height;
  
  var newStatus = percentage_value > 15 ? 2 : 1;
  if(newStatus == status)
    return;
  switch(newStatus) {
    case 1:
      TweenMax.to(".bar", 2, {right:"-125%", ease:Power2.easeOut});
      break;
    case 2:
      // because this function got called all the time, the animation started all over again, each frame.
      // And becase the animation starts slowly it stayed slow as long as the user scrolled.
      TweenMax.to(".bar", 3, {right:"0", ease:Bounce.easeOut});
      break;
  }
  status = newStatus;
});
.foo {
  height: 2000px;
}
.bar {
  background-color: red;
  height: 50px;
  width: 50px;
  position: fixed;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
  Test<br />
  Test
  <div class="bar">
  </div>
</div>

顺便说一句: 由于令人讨厌的每帧问题,如果不计算 $(document)$(document).height()$(window) 的值,您可以 显着 提高性能] 在那个函数里面。我建议将所有这些代码的范围限定在

之类的包装中
(function() {
  var jDocument = $(document),
      content_height = jDocument.height(),
      jWindow = $(window),
      status = 0;
  // [CODE HERE, using jWindow instead of $(window)]
})();

这也解决了问题,否则 status 要么需要一个又长又复杂的名称,要么就有被其他人的代码覆盖的危险。

PS:我不得不承认,我不喜欢你现在的动画。它对我来说弹跳太多了 - 甚至太多了,我根本看不到它弹跳。对我来说它好像出现了又消失了,我第一次看到它。