JS实战——选项卡的简单实现

  选项卡在页面中很常见,今天学习了下,记录下来。代码如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7   <title>选项卡</title>
 8   <style>
 9     #container div {
10        300px;
11       height: 200px;
12       border: 3px solid red;
13       display: none;
14       margin-top: 10px;
15       text-align: center;
16       line-height: 200px;
17       font-size: 30px;
18     }
19 
20     #container div.active {
21       display: block;
22     }
23 
24     button {
25       outline: none;
26       border: 2px solid gray;
27       border-radius: 5px;
28     }
29 
30     button.active {
31       background-color: orange;
32     }
33   </style>
34 </head>
35 <body>
36   <div id="wrap">
37     <button class="active">选项一</button>
38     <button>选项二</button>
39     <button>选项三</button>
40     <button>选项四</button>
41     <div id="container">
42       <div class="active">内容一</div>
43       <div>内容二</div>
44       <div>内容三</div>
45       <div>内容四</div>
46     </div>
47   </div>
48   <script>
49     var oWrap = document.getElementById('wrap')
50     var oBtn = oWrap.getElementsByTagName('button')
51     var oCon = document.getElementById('container')
52     var oDiv = oCon.getElementsByTagName('div')
53     for (var i = 0; i < oBtn.length; i++) {
54       oBtn[i].index = i
55       oBtn[i].onclick = function () {
56         for (var j = 0; j < oBtn.length; j++) {
57           oBtn[j].style.backgroundColor = 'white'
58           oDiv[j].style.display = 'none'
59         }
60         this.style.backgroundColor = 'orange'
61         oDiv[this.index].style.display = 'block'
62       }
63     }
64   </script>
65 </body>
66 </html>

效果如下:

  这里只是简单记录,代码还不够精简,见谅。

原文地址:https://www.cnblogs.com/pcyu/p/11306165.html