carloadl的onload setInterval

时间:2015-09-26 22:02:43

标签: javascript html carousel

我正在乱搞并从头开始制作一个简单的旋转木马。起初我使用onclick="function()"切换图像,然后我想将其切换为onload="setInterval(function, 4000)",但这似乎已经破坏了某些内容......

这是html:

<div id="carousel">
    <div class="carousel-image" onload="setInterval(newImage(this), 4000)"><img src="http://placehold.it/350x150">1</div>
    <div class="carousel-image-off" onload="setInterval(newImage(this), 4000)"><img src="http://placehold.it/350x150">2</div>
    <div class="carousel-image-off" onload="setInterval(newImage(this), 4000)"><img src="http://placehold.it/350x150">3</div>
    <div class="carousel-image-off" onload="setInterval(newImage(this), 4000)"><img src="http://placehold.it/350x150">4</div>
    <div class="carousel-image-off" onload="setInterval(newImage(this), 4000)"><img src="http://placehold.it/350x150">5</div>
    <div class="carousel-image-off" onload="setInterval(newImage(this), 4000)"><img src="http://placehold.it/350x150">6</div>
</div>

以下是剧本:

<script>
        var arr = 0;
        function newImage(el){
            var images = document.getElementById('carousel').children;
            for (var i = 0; i < images.length; i++ ){
                images[i].className = "carousel-image-off";
            } if (arr < images.length-1){
                arr++;
                images[arr].className = "carousel-image";
            } else {
                arr = 0;
                images[arr].className = "carousel-image";
            }
        }
</script>

1 个答案:

答案 0 :(得分:2)

我已经简化了一些,改变了一些事情。

<强> HTML

<div id="carousel">
    <div class="carousel-image active"><img src="http://placehold.it/350x150">1</div>
    <div class="carousel-image"><img src="http://placehold.it/350x150">2</div>
    <div class="carousel-image"><img src="http://placehold.it/350x150">3</div>
    <div class="carousel-image"><img src="http://placehold.it/350x150">4</div>
    <div class="carousel-image"><img src="http://placehold.it/350x150">5</div>
    <div class="carousel-image"><img src="http://placehold.it/350x150">6</div>
</div>

<强> CSS

.carousel-image {
    display:none;
}
.carousel-image.active {
    display:inline;
}

<强>的JavaScript

function newImage() {
    var images = document.getElementsByClassName('carousel-image');
    for(var i = 0; i < images.length; i++ ) {
        if(images[i].className.match('active'))
        {
            images[i].classList.remove('active');
            if(i >= images.length-1)
            {
                images[0].classList.add('active');
            }
            else
            {
                images[i+1].classList.add('active');
            }
            break;
        }
    }
}

setInterval(
    newImage, 
    1000
);

<强>的jsfiddle

http://jsfiddle.net/nasd0ska/2/

注意

如果我是你,我会使用jQuery。操作DOM非常简单方便!