原生tab欄切換 css 1 <style> 2 .box { 3 width: 400px; 4 margin:100px auto; 5 border:1px solid #ccc; 6 } 7 .top button.purple { 8 background-color: purple; 9 ...
原生tab欄切換
css
1 <style> 2 .box { 3 width: 400px; 4 margin:100px auto; 5 border:1px solid #ccc; 6 } 7 .top button.purple { 8 background-color: purple; 9 } 10 .bottom div{ 11 width:100%; 12 height: 300px; 13 background-color: pink; 14 display: none; 15 } 16 .bottom div.show{ 17 display:block; 18 } 19 20 </style>
html
1 <div class="box"> 2 <div class="top" id="top"> 3 <button class="purple">第一個</button> 4 <button>第二個</button> 5 <button>第三個</button> 6 <button>第四個</button> 7 <button>第五個</button> 8 </div> 9 <div class="bottom" id="divs"> 10 <div class="show">1號盒子</div> 11 <div>2號盒子</div> 12 <div>3號盒子</div> 13 <div>4號盒子</div> 14 <div>5號盒子</div> 15 </div> 16 </div>
js
1 <script> 2 function Tab(){ 3 this.btns = document.getElementById("top").children; 4 this.divs = document.getElementById("divs").children; 5 this.init = function(){ 6 for(let i = 0; i < this.btns.length; i++){ 7 this.btns[i].onclick = function(){ 8 this.clearAll(); 9 this.showFn(i);/ 10 }.bind(this) 11 } 12 } 13 this.clearAll = function(){ 14 for(var i = 0; i < this.btns.length; i++){ 15 this.btns[i].className = ""; 16 this.divs[i].className = ""; 17 } 18 } 19 this.showFn = function(index){ 20 //this是實例, 看showFn執行有沒有點,有點,showFn點前面的this;點前面的this是實例 21 this.btns[index].className = "purple"; 22 this.divs[index].className = "show" 23 } 24 } 25 var res = new Tab(); 26 res.init(); 27 </script>