问题
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.
<!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>
回答1:
<!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>
回答2:
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.
A working example is here: 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);
来源:https://stackoverflow.com/questions/19591598/rotating-images-in-html