本文實例為大家分享了JavaScript實現切換多張圖片的具體代碼,供大家參考,具體內容如下
循環切換圖片
HTML+CSS+JavaScript
html部分
1
2
3
4
5
6
7
8
9
10
|
< body > < div class = "outer" > < p id = "info" ></ p > < img src = "./images/banner1.png" alt = "圖片" title = "圖片" > < button id = 'prev' >上一張</ button > < button id = 'next' >下一張</ button > </ div > </ body > |
css部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<style> * { padding : 0 ; margin : 0 ; } .outer { width : 1000px ; background-color : #bfa ; margin : 50px auto ; text-align : center ; padding : 10px ; } img { width : 900px ; display : block ; margin : 0 auto ; } button { margin : 5px ; } </style> |
JavaScript部分
這里用到了JavaScript的DOM對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<script> // 加載文檔 window.onload = function () { //獲取img標簽 var img = document.getElementsByTagName( "img" )[0]; //創建一個數組保存所有圖片的路徑 //這里設置圖片文件的路徑 var imgArr = [ "./images/banner1.png" , "./images/banner2.png" , "./images/banner3.png" , "./images/banner4.png" , "./images/banner5.png" ]; //設置圖片初始值 var index = 0; //獲取id為info的p標簽 var info = document.getElementById( "info" ); info.innerHTML = "一共" + imgArr.length + "張," + "當前為第" + (index + 1) + "張" ; //綁定兩個按鈕 //上一張 document.getElementById( "prev" ).onclick = function () { index--; //判斷index是否小于0 if (index < 0) { index = imgArr.length - 1; //循環(第一張-》最后一張) } img.src = imgArr[index]; info.innerHTML = "一共" + imgArr.length + "張," + "當前為第" + (index + 1) + "張" ; }; //下一張 document.getElementById( "next" ).onclick = function () { index++; //判斷index是否大于數組的長度-1(數組的最大下標) if (index > imgArr.length - 1) { index = 0; //循環(最后一張-》第一張) } img.src = imgArr[index]; info.innerHTML = "一共" + imgArr.length + "張," + "當前為第" + (index + 1) + "張" ; } }; </script> |
預覽效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_45908053/article/details/113173940