js面向物件的選項卡
阿新 • • 發佈:2019-01-04
前言:
選項卡在專案中經常用到,也經常寫,今天在github突然看到一個面向物件的寫法,值得收藏和學習。
本文內容摘自github上的
html程式碼如下:
<div class="tab_wrap"> <div class="tab_item" id="tab1"> <div class="btns"> <span class="active">選單1</span> <span>選單2</span> <span>選單3</span> </div> <div class="container"> <p class="active">11111</p> <p>22222</p> <p>33333</p> </div> </div> <divclass="tab_item" id="tab2"> <div class="btns"> <span class="active">欄目一</span> <span>欄目二</span> <span>欄目三</span> <span>欄目四</span> </div> <div class="container"> <p class="active">內容一</p> <p>內容二</p> <p>內容三</p> <p>內容四</p> </div> </div> </div>
css程式碼如下:
.tab_wrap { /*width: 60%;*/ margin: 0 auto; background-color: #f0f0f0; display: flex; } .tab_item { width: 300px; box-shadow: 2px 0px 4px rgba(0, 0, 0, 2); margin: 0 40px; } .btns { display: flex; align-items: center; justify-content: center; } .btns span { flex: 1; display: block; text-align: center; border-bottom: 2px solid #000; padding: 5px 0; transition: 200ms; cursor: default; } .btns span:hover { border-bottom: 2px solid rgb(46, 131, 242); } .btns span.active { border-bottom: 2px solid rgb(46, 131, 242); background-color: rgba(46, 131, 242, .2); } .container { height: 260px; } .container p { display: none; padding: 0; margin: 0; width: 100%; height: 100%; text-align: center; line-height: 260px; } .container p.active { display: block; }
重點來了,js程式碼如下:
<script> // 建構函式 function Tab(item){ var tab = document.getElementById(item); this.btns = tab.querySelectorAll('span'); this.texts = tab.querySelectorAll('p'); this.prev = 0; this.len = this.btns.length; this.current = 0; return this; } Tab.prototype.toTap = function(){ var _this = this; for (var i = 0; i < this.len; i++) { this.btns[i].index = i; this.btns[i].onclick = function(){ _this.play(this.index) } } } Tab.prototype.play = function (index) { this.btns[this.prev].classList.remove('active'); this.texts[this.prev].classList.remove('active'); this.btns[index].classList.add('active'); this.texts[index].classList.add('active'); this.prev = index; } var tab1 = new Tab('tab1'); tab1.toTap(); var tab2 = new Tab('tab2'); tab2.toTap(); </script>
總結:
該方法程式碼簡潔語義明瞭。定義一個建構函式,在該函式原型上新增方法。在需要的地方new一個例項即可,可重用性非常高。