使用jQuery旋转Divs [英] Rotating Divs using jQuery

查看:89
本文介绍了使用jQuery旋转Divs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单容易.

我正在尝试在div内旋转图像,并在到达数组末尾时循环回到第一个图像.有人可以帮我指出我的代码在哪里出问题吗?看来,当到达第二张图片时,索引再也不会返回零以再次从数组中的第一张图片开始.

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

    });
});
}

每5秒调用一次setInterval.

This is being called with a setInterval every 5 seconds.

 setInterval (rotateImage, 5000);

非常感谢!

推荐答案

在使用索引之前,您需要检查索引是否超出范围..

You need to check if the index has broken out of bounds before using it ..

function rotateImage()
{

  $(images[index]).fadeOut('fast', function()
   {
       index++;
       if (index == images.length)
           {
               index = 0;
           }
       $(images[index]).fadeIn('fast');
   });
}

这是因为当您的函数被调用并且index为1时,它将变为2,然后尝试淡入images[2],这将失败...

that is because when your function got called and index was 1 it would be come 2 and then try to fade in the images[2] which would fail ...

这篇关于使用jQuery旋转Divs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆