我有一个清单:
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
我制作了一个代码,当页面加载时会尝试显示image1,但是在3秒内,图像会变为列表中的下一个图像。但是当代码运行时,它被卡在image1上并且在接下来的3秒内没有改变。
到目前为止,这是我的JavaScript代码:
<html>
<body>
<body onload = "myFunction()">
<img src ="image1.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
setTimeout("myFunction", 3000)
}
window.onLoad = function(){
myFunction();
}
</script>
</body>
</html>
我见过类似的代码但回答的答案不符合我的规范。
答案 0 :(得分:2)
您可以使用setInterval
(传递函数而不是字符串)而不是递归调用setTimeout
。另请注意,使用模(counter
)运算符可以大大简化%
逻辑:
<html>
<body>
<img src="image1.png" alt="image1.png" id="target">
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
var target = document.getElementById("target")
setInterval(function myFunction() {
counter = (counter + 1) % images.length
target.src = target.alt = images[counter]
}, 3000)
</script>
</body>
</html>
答案 1 :(得分:1)
在setInterval
中,您需要将函数myFunction
作为参数传递,不是函数名称"myFunction"
:
将其更改为:
setTimeout(myFunction, 3000);
答案 2 :(得分:1)
setTimeout - 只能工作一次 setInterval - 将一直持续
<html>
<body>
<img src ="logo.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["logo.png", "222.jpg"];
function myFunction() {
counter++;
if (counter > 1) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
function my2(){
setInterval("myFunction()", 1000);
}
window.onload = function(){
my2();
}
</script>
</body>
</html>
答案 3 :(得分:0)
扩展其他人已提及的内容。
更新到
setTimeout(myFunction, 3000);
将其放在您的window.onload
JS:
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
}
window.onload = function(){
setTimeout(myFunction, 3000)
}
答案 4 :(得分:0)
您可以使用setInterval
代替setTimeout
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 3) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
setInterval(myFunction, 3000);