JavaScript 尺寸动画的问题
我正在编写一个 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';
}
我现在能告诉你的是参数(元素、宽度、高度、时间范围)运行良好,这取决于我的算法。任何帮助都会很棒,谢谢!
I am in the middle of writing a JavaScript library and I have hit a problem, I have a function that resizes elements, that all works good but I also have and animated version that resizes them over a specified time frame. The script seems to freeze when ever it is run and it seems to be down to my while loop, here is my code.
// 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';
}
All I can tell you now are that the arguments (element, width, height, timeframe) are working fine, it is down to my algorithm. Any help will be great, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该是
d.getTime() <= endtime
。强调
<=
而不是>=
。此外,您需要在循环内获取新的时间戳,因为
d.getTime()
将始终相同(创建时的时间)。所以
但是你应该使用超时/间隔来制作动画,而不是循环,因为这会阻止其余脚本的执行。
这里有一些关于使用
setTimeout
和setInterval 进行动画的教程
It should be
d.getTime() <= endtime
.Emphasis on
<=
instead of>=
.Additionally you need to get a new timestamp inside the loop, as the
d.getTime()
will always be the same (the time at the moment it was created)..so
But you should use a timeout/interval to animate and not a loop as that would block the rest of the scripts from executing..
Here are a couple of tutorials about animation with
setTimeout
andsetInterval