如何在HTML中每3秒更换一次图像 [英] How to make an image change every 3 sec in HTML
问题描述
我有3张照片,我希望它们每3秒更换一次。
我有以下代码也可以,但它们会影响我的其他一些代码。我不知道为什么。
有人可以帮我解决另一个问题。
我不是一个程序员所以请轻松解释一下。谢谢
我的尝试:
Html
< script type =text / javascript>
var picPaths = ['iphone1.png','iphone2.png','iphone3 .png'];
var curPic = -1;
//预加载图像以获得流畅的动画
var imgO = new Array() ;
for(i = 0; i< picPaths.length; i ++){
imgO [i] = new Image();
imgO [i] .src = picPaths [i];
}
函数swapImage(){
curPic =(++ curPic> picPaths.length-1)? 0:curPic;
imgCont.src = imgO [curPic] .src;
setTimeout(swapImage,2000);
}
window.onload = function(){
imgCont = document.getElementById('imgBanner');
swapImage( );
}
< / script>
body < br $>
Hi,
I have 3 pictures and I want them to change every 3 sec.
I have the following codes which also works but they re influencing some of my other codes. I don't know why.
Can someone help me with another solution.
I am not a programmer so please explain things easy. thanks
What I have tried:
Html
<script type="text/javascript">
var picPaths = ['iphone1.png','iphone2.png','iphone3.png'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,2000);
}
window.onload=function() {
imgCont = document.getElementById('imgBanner');
swapImage();
}
</script>
body
< img id =imgBannersrc =alt =width =350height = 456/>
<img id="imgBanner" src="" alt="" width="350" height="456" />
CSS
#imgBanner {
职位:绝对;
右:80px;
top:836px;
z-index:9999;
填充:0;
}
CSS
#imgBanner {
position:absolute;
right: 80px;
top:836px;
z-index:9999;
padding: 0;
}
推荐答案
你可以利用javascript的内置方法setInterval来实现这个目标。
他这是我能想到的快速解决方案,
如果您有任何疑问,请告诉我。
You can utilize javascript's in-built method setInterval to accomplish this.
Here's a quick solution that I can think of,
Let me know if you 've any questions.
// Initialize images in an array
var picPaths = ['iphone1.png','iphone2.png','iphone3.png'];
// An index to track the contender image
var imageIndex = 0;
var bannerImage;
// An event callback for starting the interval
function startInterval() {
setInterval(displayNextImage, 3000);
}
function displayNextImage() {
bannerImage.src = picPaths[imageIndex];
if(imageIndex === (picPaths.length-1)) {
imageIndex = 0;
}
else {
imageIndex = imageIndex + 1; // It can be replaced with imageIndex ++
}
}
window.onload=function() {
bannerImage = document.getElementById('imgBanner');
startInterval();
}
这篇关于如何在HTML中每3秒更换一次图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!