我正在尝试使用JavaScript构建滑块模块。一切正常,但动画是线性的,并不会感觉平滑或自然。我曾想过挂钩缓和方程,但我不知道它在哪里。
这是我借用from here的动画功能:
function animate(elem, style, unit, from, to, time) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if (step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
缓动函数from here:
/**
* @param {Number} t The current time
* @param {Number} b The start value
* @param {Number} c The change in value
* @param {Number} d The duration time
*/
function easeInCubic(t, b, c, d) {
t /= d;
return c*t*t*t + b;
}
我尝试传递我已经拥有的值:
elem.style[style] = easeInCubic(start, from, to, time) + unit;
但显然,那是错的(我在数学方面并不陌生,而且我承认只是在猜测。)
我如何将两者结合在一起?
答案 0 :(得分:2)
你的方法没问题,你只是使用了错误的参数。 如上所述,t是当前时间,d是整体动画时间
function animate(elem, style, unit, from, to, time) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = easeInCubic(step*time, from,step*(to-from), time)+unit;
if (step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
答案 1 :(得分:2)
t
是当前时间,或更准确地说是已用时间。在您的情况下new Date().getTime() - start
c
是开始和结束之间的区别,在您的情况下为from - to
。
var elapsedTime = new Date().getTime() - start;
elem.style[style] = easeInCubic(elapsedTime, from, to - from, time) + unit;
if (elapsedTime >= time) clearInterval(timer);