Animate scrollLeft of a container from point A to B

故事扮演 提交于 2020-01-05 09:27:48

问题


I have a scrollable container whose scrollLeft changes from the currentValue to currentValue + 10 on each requestAnimationFrame tick (read interval).

However, this transition produces a staggered effect leading to the scrolling happening in an instant instead of animating from currentValue to currentValue + 10. Is there a way to define an easing function in this case just like we do for transitions?

Also, I need to do this without jQuery.


回答1:


Sure you can, but you need to know the percentage of how far the animation has gone. Here is a simple method for animations that takes in an object with callbacks and animation duration in seconds.

/**
* @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);
}

You then combine this method with Robert Penner's Easing Functions: https://gist.github.com/gre/1650294

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

And a final method could look something like this:

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);
  }
}


来源:https://stackoverflow.com/questions/46068631/animate-scrollleft-of-a-container-from-point-a-to-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!