javascript 在 html 中旋转图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19591598/
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
rotating images in html
提问by user2863675
hello everyone i'm trying to get these images to rotate every 5 seconds in HTML, using javascript. I cant figure out why images are not rotating, if someone could assist me that would be great!! thank you.
大家好,我正在尝试使用 javascript 使这些图像在 HTML 中每 5 秒旋转一次。我不知道为什么图像不旋转,如果有人可以帮助我那就太好了!!谢谢。
<!DOCTYPE html>
<html>
<head>
<title>Concert Ads</title>
<script type="text/javascript">
var image1=new Image()
image1.src="concert1.gif"
var image2=new Image()
image2.src="concert2.gif"
var image3=new Image()
image3.src="concert3.gif"
var image4=new Image()
image4.src="concert4.gif"
var image5=new Image()
image5.src="concert5.gif"
</script>
</head>
<body>
<img src="concert1.gif" name="slide" >
<script type="text/javascript">
var step=1
function slideit() {
document.images.slide.src=eval("image"+step+".src")
if(step<5)
step++
else
step=1
setTimeout("slideit()",5000)
slideit()
</script>
</body>
</html>
回答by Michael Besteck
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var image1 = new Image()
image1.src = "dummyImg1.jpg"
var image2 = new Image()
image2.src = "dummyImg2.jpg"
var image3 = new Image()
image3.src = "dummyImg3.png"
</script>
</head>
<body>
<img src="dummyImg1.jpg" name="slide" >
<script type="text/javascript">
var step = 1
function slideit() {
document.images["slide"].src = eval("image" + step + ".src")
if (step < 3)
step++
else
step = 1
setTimeout("slideit()", 5000)
}
slideit()
</script>
</body>
</html>
回答by Dominic Green
Your setTimeout function is incorrect, as you are passing it a string, not a function, and you don't close your function. It is also very inefficient to create a new image item every time; an array will suit you much better. Finally, I think you want to use setInterval not setTimeout.
您的 setTimeout 函数不正确,因为您传递的是字符串而不是函数,并且您没有关闭函数。每次创建一个新的图像项也是非常低效的;一个数组会更适合你。最后,我认为您想使用 setInterval 而不是 setTimeout。
A working example is here: http://jsfiddle.net/HUP5W/2
一个工作示例在这里:http: //jsfiddle.net/HUP5W/2
Obviously, the images don't work, but, if you look at the console, it is working correctly.
显然,图像不起作用,但是,如果您查看控制台,它可以正常工作。
var image = document.getElementById("img1");
var src = ["concert2.gif","concert3.gif","concert4.gif","concert5.gif","concert1.gif"];
var step=0
function slideit() {
image.src = src[step];
image.alt = src[step];
if(step<4) {
step++;
} else {
step=0;
}
}
setInterval(slideit,5000);