JavaScript数组实现图片轮播

时间:2023-03-09 06:46:03
JavaScript数组实现图片轮播

最终效果

JavaScript数组实现图片轮播

注:图片来源于百度图片

文件结构:

JavaScript数组实现图片轮播

代码:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片轮播</title>
<style>
div{
width: 900px;
height: 400px;
margin: 0 auto;
}
div img{
width: 900px;
height: 400px;
} </style>
<script> function init(){
//window.setTimeout(changeImage,2000);//只调用一次
window.setInterval(changeImage,2000);//每隔2000ms,可以调用多次
}
var pathArr=new Array("../images/1.jpg","../images/2.jpg","../images/3.jpg","../images/4.jpg"); var index=0;
function changeImage(){
nextImg(); } function preImg(){
myimg=document.getElementById("myimg");
index--; if(index<=0){
index=pathArr.length-1; }
myimg.src=pathArr[index];
}
function nextImg(){
myimg=document.getElementById("myimg");
index++; if(index>=pathArr.length){
index=0;
}
myimg.src=pathArr[index];
} </script> </head>
<body onload="init()">
<p align="center">
<button onclick="preImg()">上一张</button>
<button onclick="nextImg()"> 下一张</button> </p>
<div> <img src="../images/1.jpg" id="myimg" />
</div>
</body>
</html>