使用setinterval进行图像幻灯片放映

时间:2013-02-06 09:09:08

标签: javascript

我正在尝试使用javascript创建一个简单的图片幻灯片,但它不起作用。

<script>
var image=document.getElementById("aaa");
var img_array=["images/Chrysanthemum.jpg","images/desert.jpg","images/koala.jpg","images/penguins.jpg","images/hydrangeas.jpg","images/lighthouse.jpg","images/jellyfish.jpg"];
var index=0;
function slide()
{
    image.setAttribute("src",img_array[index]);
    index++;
    if(index>=img_array.length)
    {
    index=0;
    }
}
setInterval("slide()",2000);
</script>
</head>
<body>
<img id="aaa" src="images/tulips.jpg" width="400" height="400" name="image" />
</body>

5 个答案:

答案 0 :(得分:3)

简单的方法:

window.onload = function() {
    var image=document.getElementById("aaa");
    var img_array=[...];
    var index=0;
    var interval = 2000;
    function slide() {
        image.src = img_array[index++%img_array.length];
    }

    setInterval(slide, interval);
}

更好的方法:

setInterval(slide,2000);更改为:

setTimeout(function() {
    slide();
    setTimeout(arguments.callee, interval)
}, interval);

答案 1 :(得分:2)

Hello bellow是您的代码的固定版本。

<script>
var image = document.getElementById("aaa");
var img_array=["http://png-4.findicons.com/files/icons/1008/quiet/256/java.png","http://icons.iconarchive.com/icons/tpdkdesign.net/refresh-cl/256/System-Java-icon.png"];
var index=0;
function slide()
{

    document["aaa"].src = img_array[index];
    index++;
    if(index>=img_array.length)
    {
    index=0;
    }
}
setInterval("slide()",2000);
</script>
</head>
<body>
<img id="aaa" src="http://www.tutorialsscripts.com/free-icons/programming-language/java-icons/purple-java-icon-256-x-256.gif" width="400" height="400" name="image" />

答案 2 :(得分:0)

使用以下

替换您的setinterval调用
setInterval(function(){slide()},2000);

答案 3 :(得分:0)

代替

setInterval("slide()",2000);

放入

setInterval(slide,2000);

答案 4 :(得分:-2)

代码:

function slideshow()
{
    var slides= ["background-image : url(image/1.jpg)","background-image : url(image/2.jpg)"];
    var i = 0;
    var divh = document.getElementById("demo").style ;
    while( i < slides.length)
    {           
        if( i == (slides.length-1) )
            {
                divh = slides[i];
                i = 0;
            }
        else
        {
            divh = slides[i];
             i++ ;
        }                      
    }
}