點擊實現(xiàn)圖片切換效果在生活中非常的常見,恰巧今天的練習(xí)也是做一個圖片的切換效果。供大家參考:
HTML代碼如下:
1
2
3
4
5
6
7
|
< div class = "img" > < img src = "images/1.jpg" id = "myImg" class = "myImg" alt = "這里是1.jpg" > < p > < input type = "button" id = "pre" class = "btn" value = "上一張" > < input type = "button" id = "next" class = "btn" value = "下一張" > </ p > </ div > |
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
25
26
27
28
29
30
31
32
33
|
*{ margin : 0 ; padding : 0 ; } img{ boder: none ; } button{ outline : none ; vertical-align : middle ; } .img{ width : 100% ; margin-left : auto ; margin-right : auto ; margin-top : 20px ; text-align : center ; } .myImg{ width : 500px ; height : 300px ; } p{ text-align : center ; } p .btn{ width : 100px ; height : 30px ; background : #306bbf ; color : #fff ; margin-top : 20px ; margin-bottom : 20px ; } |
javascript 部分:
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
|
//找標(biāo)簽 let myImg = document.getElementById( "myImg" ); let pre=document.getElementById( "pre" ); let next=document.getElementById( "next" ); //創(chuàng)建一個保存圖片的數(shù)組 let arrImg = [ "images/1.jpg" , "images/1-1.png" , "images/3.jpg" ]; //數(shù)組的索引下標(biāo) let index=0; //定義事件函數(shù) function preImg(event){ index--; //實現(xiàn)循環(huán)切換 if (index<0) { index=arrImg.length-1; } myImg.src = arrImg[index]; } function nextImg(event){ index++; //實現(xiàn)循環(huán)切換 if (index>arrImg.length-1) { index=0; } myImg.src = arrImg[index]; } pre.addEventListener( 'click' ,preImg); next.addEventListener( 'click' ,nextImg); |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/Lzy_o/article/details/115408535