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

时间:2015-02-02 19:06:28

标签: javascript jquery greensock tweenmax gsap

我的动画事件几乎暂停或让我们说当滚动达到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})

    }
});

1 个答案:

答案 0 :(得分:1)

这里是解决方案的演示并解释评论:



// 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>
&#13;
&#13;
&#13;

顺便说一下: 如果你不计算$(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:我必须承认,我不喜欢当前状态下的动画。它对我来说反弹太多 - 即使那太多​​,我根本看不到它弹跳。对我来说,它似乎出现并消失了,这是我第一次看到它。