动画容器的scrollLeft从A点到B

时间:2017-09-06 06:52:41

标签: javascript animation scroll

我有一个可滚动的容器,scrollLeft在每个currentValue刻度线(读取间隔)上从currentValue + 10更改为requestAnimationFrame

但是,此转换会产生交错效果,导致滚动瞬间发生,而不是从currentValue动画到currentValue + 10。有没有办法在这种情况下定义缓动函数,就像我们为转换做的那样?

另外,我需要在没有jQuery的情况下这样做。

1 个答案:

答案 0 :(得分:2)

当然可以,但你需要知道动画走了多远的百分比。这是一个简单的动画方法,它接收一个具有回调和动画持续时间的对象,以秒为单位。

/**
* @param callbackObj Object An object with callbacks in .start, .progress, and .done
* @param duration Integer Total duration in seconds
*/
function animate(callbackObj, duration) {
        var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
        var startTime = 0, percentage = 0, animationTime = 0;

        duration = duration*1000 || 1000;

        var animation = function(timestamp) {

          if (startTime === 0) {
              startTime = timestamp;
            } else {
              animationTime = timestamp - startTime;
            }

          if (typeof callbackObj.start === 'function' && startTime === timestamp) {
             callbackObj.start();

             requestAnimationFrame(animation);
          } else if (animationTime < duration) {
             if (typeof callbackObj.progress === 'function') {
               percentage = animationTime / duration;
               callbackObj.progress(percentage);
             }

            requestAnimationFrame(animation);
          } else if (typeof callbackObj.done === 'function'){
              callbackObj.done();
          }
        };

      return requestAnimationFrame(animation);
}

然后,您将此方法与Robert Penner的缓和函数结合使用:https://gist.github.com/gre/1650294

function easeInOutQuad(t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },

最后一种方法看起来像这样:

function sideScroll(rangeInPixels) {
  var element = document.getElementById('scrollableContainer');

  if (element) {
    var sequenceObj = {};
    var seconds = 0.3;
    var startingScrollPosition = element.scrollY;

    sequenceObj.progress = (function(percentage) {
      element.scroll( (startingScrollPosition + easeInOutQuad(percentage))*rangeInPixels) , 0);
    }

    animate(sequenceObj, seconds);
  }
}