javascript实战——简单图片轮播实现
效果展示:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>标题</title> 6 <style> 7 div{ 8 width: 900px; 9 height: 400px; 10 margin: 0px auto; 11 } 12 div img{ 13 margin: 0px auto; 14 width: 900px; 15 height: 400px; 16 } 17 </style> 18 <script type="text/javascript"> 19 var arr = new Array("路径1","路径2","路径3","路径4",....); 20 //设置图片更换时间-4s。定义初始化方法在body加载完成后再调用,以免body未加载完成导致图片更换失败 21 function init(){ 22 window.setInterval(changeImg,4000); 23 } 24 //定义变量,当图片轮播至最后一张图片时从第一张开始重新轮播 25 var index = 0; 26 function changeImg() { 27 nextImg() 28 } 29 function preImg() { 30 var img = document.getElementById("img"); 31 index -= 1; 32 if (index<0){ 33 index = arr.length-1; 34 }img.src=arr[index] 35 } 36 function nextImg() { 37 var img = document.getElementById("img"); 38 index ++; 39 if (index>=arr.length){ 40 index = 0; 41 }img.src=arr[index] 42 } 43 </script> 44 </head> 45 <body onload="init()"> 46 <div> 47 <p align="center"> 48 <button onclick="preImg()">上一张</button> 49 <button onclick="nextImg()">下一张</button> 50 </p> 51 <img src="img/1.jpg" id="img"> 52 </div> 53 </body> 54 </html>