使用 jQuery 旋转 Div
简单易行的一种。
我试图在 div 内旋转图像,并在到达数组末尾时循环回到第一个图像。有人可以帮我指出我的代码哪里出了问题吗?似乎当它到达第二个图像时,索引永远不会返回到零以再次从数组中的第一个图像开始。
var images = new Array ('.advert1', '.advert2');
var index = 0;
function rotateImage()
{
$(images[index]).fadeOut('fast', function()
{
index++;
$(images[index]).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
});
});
}
每 5 秒调用一次 setInterval。
setInterval (rotateImage, 5000);
非常感谢!
Simple easy one.
I am trying to rotate image inside divs and cycle back to the first one when the end of my array has been reached. Can someone please help point me out where I am going wrong in my code here? It seems that when it gets to the second image, the index never returns back to zero to start with the first image in my array again.
var images = new Array ('.advert1', '.advert2');
var index = 0;
function rotateImage()
{
$(images[index]).fadeOut('fast', function()
{
index++;
$(images[index]).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
});
});
}
This is being called with a setInterval every 5 seconds.
setInterval (rotateImage, 5000);
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在使用索引之前检查索引是否超出范围..
那是因为当您的函数被调用并且
index
为 1 时,它将变为 2,然后尝试淡入images[2]
会失败......You need to check if the index has broken out of bounds before using it ..
that is because when your function got called and
index
was 1 it would be come 2 and then try to fade in theimages[2]
which would fail ...