使用 setTimeout 函数。 &随机函数为类元素添加动画
我的调试技巧并不能帮助我弄清楚我在这里做错了什么。
我希望数组中的每个元素使用 setTimeout 函数在指定时间后进行动画处理。
我没有收到任何错误,并且循环似乎运行得很好,但是,数组中的任何元素最终都不会从原来的位置移动到新位置。
function publicity()
{
// placing elements with class name 'cCameras' inside an array
var eCamerasArray = $(".cCameras").toArray();
// creating 2 arrays to hold left & top values of each element
var iLeftPosArray = [];
var iTopPosArray = [];
// loop to run through each element in array
for( var i = 0; i < eCamerasArray.length; i++)
{
// timer variable set for each element to be used in setTimeout func.
var timer = Math.floor (Math.random()*300) + 100;
// setTimeout func. used to animate each element after a specified (timer) time
window.setTimeout (function ()
{
iLeftPosArray[i] = Math.floor (Math.random() *139) + 360;
iTopPosArray[i] = Math.floor (Math.random() *160) + 100 ;
$(eCamerasArray[i]).animate ({left: iLeftPosArray[i] + "px", top: iTopPosArray[i] + "px"}, 100, "linear");
return [iLeftPosArray[i], iTopPosArray[i]];
}, timer);
}
}
My debugging skills are not helping me much with figuring out what I am doing wrong here.
I want each element in an array to animate after a specified time using setTimeout function.
I am not getting any errors and the loop appears to run just fine, however, none of the elements in the array end up moving from their original place to the new spot.
function publicity()
{
// placing elements with class name 'cCameras' inside an array
var eCamerasArray = $(".cCameras").toArray();
// creating 2 arrays to hold left & top values of each element
var iLeftPosArray = [];
var iTopPosArray = [];
// loop to run through each element in array
for( var i = 0; i < eCamerasArray.length; i++)
{
// timer variable set for each element to be used in setTimeout func.
var timer = Math.floor (Math.random()*300) + 100;
// setTimeout func. used to animate each element after a specified (timer) time
window.setTimeout (function ()
{
iLeftPosArray[i] = Math.floor (Math.random() *139) + 360;
iTopPosArray[i] = Math.floor (Math.random() *160) + 100 ;
$(eCamerasArray[i]).animate ({left: iLeftPosArray[i] + "px", top: iTopPosArray[i] + "px"}, 100, "linear");
return [iLeftPosArray[i], iTopPosArray[i]];
}, timer);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过创建闭包来修复它:
您可以在此处查看效果: http://jsfiddle.net/zHUAt/2 /
致以诚挚的问候!
You can fix it with creating closure:
You can see the effect here: http://jsfiddle.net/zHUAt/2/
Best regards!
展开一个简单的循环,您可以看到发生了什么:
如您所见,所有函数都引用相同的
i
,因此一旦计时器触发,它们都会记录
2
。他们都没有有一个本地
i
。您可以像这样创建一个“本地”
i
:Unrolling a simple loop you can see what happens:
As you can see, all the functions refer to the same
i
, sothey will all log
2
once the timers fire. None of themhave a local
i
.You can create a "local"
i
like this: