JavaScript数组实现图片轮播

最终效果

注:图片来源于百度图片

文件结构:

代码:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>图片轮播</title>
 6         <style>
 7             div{
 8                 width: 900px;
 9                 height: 400px;
10                 margin: 0 auto;
11             }
12             div img{
13                 width: 900px;
14                 height: 400px;
15             }
16             
17             
18             
19         </style>
20         <script>
21             
22             function init(){
23                 //window.setTimeout(changeImage,2000);//只调用一次
24                 window.setInterval(changeImage,2000);//每隔2000ms,可以调用多次
25             }
26             var pathArr=new Array("../images/1.jpg","../images/2.jpg","../images/3.jpg","../images/4.jpg");
27             
28             
29             var index=0;
30             function changeImage(){
31                 nextImg();
32                 
33                 }
34             
35             function preImg(){
36                 myimg=document.getElementById("myimg");
37                 index--;
38             
39                 if(index<=0){
40                     index=pathArr.length-1;
41                 
42             }
43                 myimg.src=pathArr[index];
44             }
45                 function nextImg(){
46                     myimg=document.getElementById("myimg");
47                 index++;
48                 
49                 if(index>=pathArr.length){
50                     index=0;
51                 }
52                 myimg.src=pathArr[index];
53                 }
54             
55             
56             
57         </script>
58         
59         
60     
61     </head>
62     <body onload="init()">
63         <p align="center">
64             <button onclick="preImg()">上一张</button>
65             <button onclick="nextImg()"> 下一张</button>
66             
67             
68         </p>
69         <div>
70             
71             <img src="../images/1.jpg" id="myimg" />
72         </div>
73     </body>
74 </html>

猜你喜欢

转载自www.cnblogs.com/jiguiyan/p/10463339.html