试图创建一个jQuery图像旋转器,但只能让它的前半部分工作

时间:2013-03-26 19:07:02

标签: jquery css image rotation

我正在尝试创建一个图像旋转器,其中一个图像将淡入下一个图像,依此类推,直到它循环回到第一个图像。我让前两个图像正常工作,但其余三个图像没有正确消失。他们只是跳进了视野。

我知道我还需要考虑到达轮换结束的时间。我还没有照顾到这一点,因为我只是试图让第一轮轮换工作。

我错过了什么才能让它正常工作?

我的HTML:

    <div id="imageRotator">
    <div id="image01" class="current">
        <img src="images/imageRotate01.jpg">
    </div>
    <div id="image02" class="next">
        <img src="images/imageRotate02.jpg">
    </div>
    <div id="image03" class="hidden">
        <img src="images/imageRotate03.jpg">
    </div>
    <div id="image04" class="hidden">
        <img src="images/imageRotate04.jpg">
    </div>
    <div id="image05" class="hidden">
        <img src="images/imageRotate05.jpg">
    </div>
</div>

我的CSS:

#imageRotator div {
    position: absolute;
}

.current {
    z-index: 1;
}

.next {
    z-index: 0;
}

.hidden {
    z-index: -1;
}

我的jQuery:

$(document).ready(function() {

    var firstImage = $('#image01');
    var currentImage, nextImage;

    setInterval(rotateImages, 2000);

    function rotateImages() {
        currentImage = $('div.current');
        nextImage = $('div.next');

        //the first image fades away
        currentImage.animate({opacity: 0}, 2000, function() {
            currentImage.removeClass('current');    
        });

        //bring the second image into view
        nextImage.animate({opacity: 1}, 2000, function() {

            //make the new image the current image
            nextImage.removeClass('next').addClass('current');

            //the next image in the rotation becomes the 'next' image
            nextImage.next().addClass('next').removeClass('hidden');
        });
    }
});

1 个答案:

答案 0 :(得分:1)

默认情况下,您没有设置零opacity,因此第一个元素之后的元素没有opacity的动画。尝试将其设置为0,除了第一个元素之外的所有元素,看看会发生什么。

#imageRotator div {
    position: absolute;
    width: 30px;
    height: 30px;
    outline:1px solid red;
    background:red;
    opacity: 0;
}
#imageRotator div:first-child{
        opacity:1;
}
.current {
    z-index: 1;
}

.next {
    z-index: 0;
}

.hidden {
    z-index: -1;
}

DEMO:http://jsfiddle.net/pavloschris/N3gXd/