在去抖动的requestanimationframe

时间:2017-02-17 21:26:01

标签: javascript animation requestanimationframe

我按照保罗刘易斯的指导去辩护和requestAnimationFrame。当它进入视图时,我正在滚动屏幕上的图像。

var bicycles = $('.tandem-bike', context),
      lastScrollY = 0,
      ticking     = false;

  function update() {
    var windowHeight  = window.innerHeight,
        windowWidth   = $(window).width(),
        bikeTop       =  [];

    bicycles.each( function (i, el) {
      bikeTop[i]            = $(this).offset();
    });

    bicycles.each(function(i, el) {

      var position = bikeTop[i];
      var fromTop = position.top - windowHeight;
      var imgHeight = $(this).height();
      // When this image scrolls into view.
      if (lastScrollY > fromTop  && lastScrollY < position.top + imgHeight && i == 1 ) { // 375 ~= height of image

        var translate = Math.floor((lastScrollY - fromTop) / ((windowHeight + imgHeight + 300) / windowWidth));
        console.log('add tp tranlate ', translate);
        $(this).css('transform', 'translateX(' + (translate - 275) + 'px)');
      }
    });

    ticking = false;
  }

  function onScroll() {
    lastScrollY = window.scrollY;
    requestTick();
  }

  function requestTick() {
    if(!ticking) {
      requestAnimationFrame(update);
      ticking = true;
    }
  }

  window.addEventListener('scroll', onScroll, false);

这非常有效,自行车可以轻松地在屏幕上滑动。但是,当用户停止滚动时,我希望图像“反弹”。我想一个简单的方法是在动画结束时添加一个类,并在动画开始时将其拉出。显而易见的地方是if中的requestTick()块。

    if(!ticking) {
      $('.tandem-bike').removeClass('bounce');
      requestAnimationFrame(update);
      $('.tandem-bike').addClass('bounce');
      ticking = true;
    } 

    if(!ticking) {
      requestAnimationFrame(update);
      $('.tandem-bike').addClass('bounce');
      ticking = true;
    } else {
      $('.tandem-bike').removeClass('bounce');
    }
  }

两者都不起作用,我不喜欢,因为我是整个销售,为页面上的所有动画图像添加类。 (如果有效,我会忍受)

0 个答案:

没有答案
相关问题