Rotating Divs using jQuery

不羁的心 提交于 2019-12-25 08:31:47

问题


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!


回答1:


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

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 ...



来源:https://stackoverflow.com/questions/4153520/rotating-divs-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!