JavaScript大小动画的问题

时间:2010-10-25 22:11:47

标签: javascript html loops while-loop

我正在编写一个JavaScript库,我遇到了一个问题,我有一个调整元素大小的函数,一切都运行良好,但我也有动画版本,可以在指定的时间范围内调整它们的大小。该脚本在运行时似乎冻结,似乎是我的while循环,这是我的代码。

// Resize in timeframe
// Work out distance
var widthDiff = width - element.offsetWidth;
var heightDiff = height - element.offsetHeight;

// Work out pixels per milisecond
var widthppm = widthDiff / timeframe;
var heightppm = heightDiff / timeframe;

// Set up times
var d = new Date();
var endtime = d.getTime() + timeframe;

// Get the original width and height
var oldwidth = element.offsetWidth;
var oldheight = element.offsetHeight;

var iteration;

// Loop through until done
while(d.getTime() >= endtime)
{
    iteration = timeframe - (endtime - d.getTime());
    element.style.width = oldwidth + (iteration * widthppm) + 'px';
    element.style.height = oldheight + (iteration * heightppm) + 'px';
}

我现在可以告诉你的是,参数(元素,宽度,高度,时间帧)工作正常,这取决于我的算法。任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:1)

应该是d.getTime() <= endtime 强调<=而不是>=

此外,您需要在循环中获取新的时间戳,因为d.getTime()将始终相同(创建时的时间)..

所以

while(d.getTime() <= endtime)
{
    iteration = timeframe - (endtime - d.getTime());
    element.style.width = oldwidth + (iteration * widthppm) + 'px';
    element.style.height = oldheight + (iteration * heightppm) + 'px';
    d = new Date();
}

但你应该使用超时/间隔来制作动画而不是循环,因为这会阻止其余的脚本执行..

以下是一些有关setTimeoutsetInterval

动画的教程