本文实例为大家分享了JS代码实现页面切换效果的具体代码,供大家参考,具体内容如下
HTML+CSS部分
添加所有页面,和上一页、具体页、下一页的按钮,
设置div样式,默认第一页显示,其他页隐藏。
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
40
41
42
43
44
45
|
<!DOCTYPE html> < html > < head > < meta charset = "UTF-8" > < title ></ title > < style > .item { display: none; width: 300px; height: 400px; overflow: hidden; position: relative; } .item>img { width: 100%; height: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } .item.active { display: block; } </ style > </ head > < body > < div > < button class = "prev" >上一页</ button > < button class = "btn" >1</ button > < button class = "btn" >2</ button > < button class = "btn" >3</ button > < button class = "btn" >4</ button > < button class = "next" >下一页</ button > </ div > < div > < div class = "item active" >< img src = "img/1.png" height = "1191" width = "820" /></ div > < div class = "item" >< img src = "img/2.png" height = "1191" width = "820" /></ div > < div class = "item" >< img src = "img/3.png" height = "1191" width = "820" /></ div > < div class = "item" >< img src = "img/4.png" height = "1191" width = "820" /></ div > </ div > </ body > </ html > |
js部分
通过按键来实现页面的功能
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
|
<script type= "text/javascript" > //封装函数、图片显示的部分、传入获取到的div,和被点击的序号 function toggle(eles, active) { for ( var i = eles.length; i--;) { eles[i].className = "item" ; //先让所有div隐藏 } eles[active].className = "item active" ; //再让被点击的序号对应的div 显示 } //获取按键和div var aBtn = document.getElementsByClassName( "btn" ); var aIem = document.getElementsByClassName( "item" ); var prev = document.getElementsByClassName( "prev" ); var next = document.getElementsByClassName( "next" ); var nowPage = 0; //定义当前页,默认值为0; for ( var i = aBtn.length; i--;) { aBtn[i].tab = i; aBtn[i].onclick= function (){ toggle(aIem, this .tab); nowPage= this .tab; //被点击后,保存当前页的序号 } } //下一页 next[0].onclick = function () { nowPage++; nowPage %= aBtn.length; toggle(aIem,nowPage); } //上一页 prev[0].onclick= function (){ nowPage--; if (nowPage ==-1){ nowPage = aBtn.length-1; } toggle(aIem,nowPage); } </script> |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_44189739/article/details/85342424