1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4       <meta charset="UTF-8">
 5       <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6       <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7       <title>Document</title>
 8       <style>
 9             #container{
10                   width: 200px;
11                   height: 150px;
12                   border: 2px dashed #ddd;
13             }
14             .btn-list{
15                   display: flex;
16                   height: 40px;
17             }
18             .btn-list button{
19                   flex: 1;
20                   line-height: 40px;
21             }
22             .btn-list button.active{
23                   background-color: crimson;
24                   color: cyan;
25             }
26             .content-list .box{
27                   width: 200px;
28                   height: 110px;
29                   display: none;
30             }
31 
32             .content-list .box.active{
33                   display: block;
34             }
35       </style>
36 </head>
37 <body>
38 
39       <div id="container">
40             <div class="btn-list">
41                   <button data-index="0" class="active">按钮1</button>
42                   <button data-index="1">按钮2</button>
43                   <button data-index="2">按钮3</button>
44             </div>
45             <div class="content-list">
46                   <div class="box active" style="background-color: aqua;">内容1</div>
47                   <div class="box" style="background-color: blueviolet;">内容2</div>
48                   <div class="box" style="background-color: cornsilk;">内容3</div>
49             </div>
50       </div>
51       <script>
52             var btn_eles = document.querySelectorAll(".btn-list button");
53             var content_eles = document.querySelectorAll(".box");
54 
55             for(var i = 0 ; i < btn_eles.length ; i ++){
56                   
57                   btn_eles[i].onmouseover = function(){
58                         reset() 
59                         this.className = "active";
60                         var index = this.getAttribute("data-index");
61                         content_eles[index].className += " active";
62                   }
63             }
64 
65             function reset(){
66                   for(var i = 0 ; i < btn_eles.length ; i ++){
67                         btn_eles[i].className = "";
68                         content_eles[i].className = "box";
69                   }
70             }
71       </script>
72 </body>
73 </html>

第22行和第32行的写法,是同级别的标签或类名先检索到,然后又标记到了想要找的类名。

posted on 2021-04-21 19:17  Topcoder-V  阅读(353)  评论(0编辑  收藏  举报