1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <script type="text/javascript"> 8 window.onload=function(){ 9 var prev=document.getElementById("prev"); 10 var next=document.getElementById("next"); 11 var img=document.getElementsByTagName("img")[0]; 12 //创建一个数组用来保存图片的路径 13 var imgArr=["1.jpg","2.png","3.jpg","4.png","5.png"]; 14 //创建一个变量,来保存当前正在显示的图片的索引 15 var index=0; 16 var info=document.getElementById("info"); 17 info.innerHTML="一共"+imgArr.length+"张图片,当前第"+(index+1)+"张"; 18 prev.onclick=function(){ 19 alert("上一张"); 20 index--; 21 if(index<0){ 22 index=imgArr.length-1; 23 } 24 info.innerHTML="一共"+imgArr.length+"张图片,当前第"+(index+1)+"张"; 25 img.src=imgArr[index]; 26 } 27 next.onclick=function(){ 28 alert("下一张"); 29 index++; 30 if(index>4)index=0; 31 info.innerHTML="一共"+imgArr.length+"张图片,当前第"+(index+1)+"张"; 32 img.src=imgArr[index]; 33 } 34 }; 35 36 </script> 37 <style type="text/css"> 38 *{ 39 margin:0px; 40 padding:0px; 41 } 42 #outer{ 43 width:1208px; 44 height:735px; 45 margin:50px auto; 46 padding:10px 10px 0px 10px; 47 background-color:yellowgreen; 48 /* 设置文本居中 */ 49 text-align:center; 50 } 51 </style> 52 <body> 53 <div id="outer"> 54 <p id="info"></p> 55 <img src="1.jpg" alt="vv" /> 56 <button id="prev">上一张</button> 57 <button id="next">下一张</button> 58 </div> 59 </body> 60 </html>