首页 > 代码库 > 常用事件【由浅入深】

常用事件【由浅入深】

一。点击变色并提示索引

技术分享html
 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title></title>
 6     <link href="StyleSheet.css" rel="stylesheet" />
 7     <style type="text/css"></style>
 8 </head>
 9 <body>
10     <div class="d1"></div>
11     <div class="d1"></div>
12     <div class="d1"></div>
13     <div class="d1"></div>
14     <div class="d1"></div>
15     <div class="d1"></div>
16 </body>
17 </html>
18 <script type="text/javascript">
19     //找到操作对象
20     var a = document.getElementsByClassName("d1");
21     //for循环遍历数组
22     for (var x = 0; x < a.length; x++) {
23         //找到对应索引
24         a[x].index = x;
25         //点击事件
26         a[x].onclick = function () {
27             //变色
28             this.style.backgroundColor = "blue";
29             //弹出索引
30             alert(this.index);
31         }
32     }
33 
34 </script>

技术分享
1 .d1 {
2     float: left;
3     width: 100px;
4     height: 30px;
5     margin-left: 10px;
6     background-color:red;
7 }
css

 

常用事件【由浅入深】