前言:

选项卡在项目中经常用到,也经常写,今天在github突然看到一个面向对象的写法,值得收藏和学习。

本文内容摘自github上的 helloforrestworld/javascriptLab ,稍作删减和整理,仅作记录和自学用途。在此感谢原作者。

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>
<div class="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:;
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:;
margin:;
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一个实例即可,可重用性非常高。

05-23 18:58