2

我正在尝试使用 JavaScript 构建一个滑块模块。一切正常,但动画是线性的,感觉不流畅或不自然。我曾想过连接一个缓动方程,但我不确定它的去向。

这是我从这里借来的动画功能:

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

以及来自这里的缓动功能:

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

但很明显,这是错误的(我的数学并不出色,我承认我只是在猜测)。

我如何将两者结合在一起?

4

2 回答 2

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;
}
于 2013-04-24T11:38:03.537 回答
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);
于 2013-04-24T11:50:05.977 回答