<!Doctype html>
<html>
<head>
<title>Slider</title>
<style>
</style>
</head>
<body>
<img id="text" alt="picture" src="cod4.jpg" style="width:900px;height:500px;">
<script>
var images = [];
images[0]= "cod2.jpg";
images[1]= "cod3.jpg";
images[2]= "cod4.jpg";
setInterval(changeimage,3000)
function changeimage(){
for(var i=0; i<=images.length; i++)
{
document.getElementById("text").src += images[i] ;
}
}
</script>
</body>
</html>
图像在 java 脚本中的给定时间后没有改变。 我尝试在 3 秒后更改图像,但它不起作用。
请帮我看看这段代码有什么问题?谢谢
最佳答案
Artem Baranovskii 发布了一个很好的答案。我不确定您是否希望图像不断循环播放,因此我会将其发布为我的答案。
var images=["http://placehold.it/150x150","http://placehold.it/170x170","http://placehold.it/190x190"];
var i=0;
//Set image and interval when the page has loaded (Is ready).
window.onload=function(){
//Call changeimage to set the first image.
changeimage();
//Set interval
setInterval(changeimage,3000);
}
function changeimage(){
//Check if i is equal to or "||" greater than array length.
if(i==images.length||i>images.length){
//If true, reset i to 0. Back to the first image in the array
i=0;
}
//Set the image url.
document.getElementById('text').src=images[i];
//Add 1 to i.
i++;
}
<img id="text" src=""/>
Comments in the source code but if you have any questions please leave a comment below and I will answer as soon as possible.
希望对您有所帮助。编码愉快!
Full source code.
<!DOCTYPE html>
<html>
<head>
<title>Slider</title>
<script type="text/javascript">
var images=["http://placehold.it/150x150","http://placehold.it/170x170","http://placehold.it/190x190"];
var i=0;
window.onload=function(){
changeimage();
setInterval(changeimage,3000);
}
function changeimage(){
if(i==images.length||i>images.length){
i=0;
}
document.getElementById('text').src=images[i];
i++;
}
</script>
</head>
<body>
<img id="text" src=""/>
</body>
</html>
关于javascript - 在 javaScript 中给定时间后图像没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31776574/