我有一个可滚动的容器,其scrollLeft
变化自currentValue
to currentValue + 10
在各个requestAnimationFrame
勾选(读取间隔)。
然而,这种过渡会产生交错效果,导致滚动立即发生,而不是从动画开始currentValue
to currentValue + 10
。在这种情况下,有没有办法像我们为过渡所做的那样定义缓动函数?
另外,我需要在没有 jQuery 的情况下执行此操作。
当然可以,但是您需要知道动画已经进行了多远的百分比。这是一个简单的动画方法,它接收带有回调的对象和动画持续时间(以秒为单位)。
/**
* @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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)