javascript 使用 setinterval 进行图像幻灯片放映
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14725230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using setinterval for image slideshow
提问by DjangoDev
I am trying to create a simple image slideshow using javascript, but it doesn't work.
我正在尝试使用 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>
回答by Rain Diao
simple way:
简单的方法:
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);
}
better way:
更好的方法:
change setInterval(slide,2000);
to:
更改setInterval(slide,2000);
为:
setTimeout(function() {
slide();
setTimeout(arguments.callee, interval)
}, interval);
回答by svlada
Hello bellow is fixed version of your code that works.
你好波纹管是你的代码的固定版本。
<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" />
回答by amit1310
Replace your setinterval call with the following
用以下内容替换您的 setinterval 调用
setInterval(function(){slide()},2000);
回答by Girish Khorate
Instead of
代替
setInterval("slide()",2000);
Put
放
setInterval(slide,2000);
回答by Hassan
Code :
代码 :
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++ ;
}
}
}