问题描述
我有一个可滚动的容器,它的scrollLeft
在每个requestAnimationFrame
刻度(读取间隔)上从currentValue
变为currentValue + 10
.
I have a scrollable container whose scrollLeft
changes from the currentValue
to currentValue + 10
on each requestAnimationFrame
tick (read interval).
但是,此过渡会产生交错效果,导致立即发生滚动,而不是从currentValue
动画到currentValue + 10
.就像我们对过渡所做的那样,有没有办法在这种情况下定义缓动函数?
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?
此外,我需要在没有jQuery的情况下进行操作.
Also, I need to do this without jQuery.
推荐答案
可以,但是您需要知道动画进行到多远的百分比.这是一种简单的动画方法,它可以接收带有回调和动画持续时间(以秒为单位)的对象.
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);
}
然后将这种方法与Robert Penner的缓动功能结合起来: https://gist.github.com/gre/1650294
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);
}
}
这篇关于动画滚动容器从点A到点B的左的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!