我是靠谱客的博主 迷人美女,这篇文章主要介绍浅谈JavaScript_DOM学习篇_图片切换小案例,现在分享给大家,希望可以做个参考。

今天开始学习DOM操作,下面写一个小案例来巩固下知识点.

DOM: document object model (文档对象模型)

根据id获取页面元素 : 如: var xx = document.getElementById("id");

根据标签获取元素: 如: var xx = document.getElementsByTagName("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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } #outer { width: 500px; /*设置上边距50px 水平居中*/ margin: 50px auto; /*设置边框*/ padding: 10px; background-color: greenyellow; /*设置文本居中*/ text-align: center; } img { width: 500px; } </style> <script>      //btn 为按钮id clickEventFunction 为点击后执行的操作函数 function addClick(btn, clickEventFunction) { var myButton = document.getElementById(btn); myButton.onclick = clickEventFunction; }; window.onload = function () { (function () { var pics = ["imgs/1.png", "imgs/2.png", "imgs/3.png"]; var index = 0; showPicNum(index); var img = document.getElementsByTagName("img")[0]; // var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); addClick("btn1", function () { index--; if (index <= -1) { index = pics.length - 1; } console.log(index + " ----- "); img.src = pics[index]; showPicNum(index); }); addClick("btn2", function () { index++; if (index >= pics.length) { index = 0; } console.log(index + " ++++++++ "); img.src = pics[index]; showPicNum(index); }); // // btn1.onclick = function () { // index --; // if(index <= -1){ // index = pics.length - 1; // } // console.log(index + " ----- "); // img.src = pics[index]; // showPicNum(index); // }; // btn2.onclick = function () { // index ++; // if(index >= pics.length){ // index = 0; // } // console.log(index + " ++++++++ "); // img.src = pics[index]; // showPicNum(index); // }; console.log(index); /** * 展示当前图片为第几张 * @param index 当前图片索引 */ function showPicNum(index) { var descrs = document.getElementById("discs"); descrs.innerText = "一共" + pics.length + "张图片,当前第" + ++index + "张"; } }()) }; </script> </head> <body> <div id="outer"> <p id="discs"></p> <img src="imgs/1.png"/><br> <button id="btn1" type="button" value="上一张">上一张</button> <button id="btn2" type="button" value="下一张">下一张</button> </div> </body> </html>

文档目录:

效果如下:

以上所述是小编给大家介绍的JavaScriptDOM图片切换小案例详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对靠谱客网站的支持!

最后

以上就是迷人美女最近收集整理的关于浅谈JavaScript_DOM学习篇_图片切换小案例的全部内容,更多相关浅谈JavaScript_DOM学习篇_图片切换小案例内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(121)

评论列表共有 0 条评论

立即
投稿
返回
顶部