兩種方式封裝瘦穆,第一種是自定義對象里的混合模式(原型模式和構(gòu)造函數(shù)模式結(jié)合),第二種是CLASS類定義對象赊豌。
以封裝選項卡功能為例
??HTML和CSS部分
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
#tab {
width: 500px;
height: 500px;
border: 1px solid black;
margin: 0 auto;
text-align: center;
}
#tab .btns {
display: flex;
justify-content: space-between;
text-align: center;
}
.btns li {
width: 33%;
height: 80px;
line-height: 80px;
background: black;
color: white;
cursor: pointer;
}
.btns li:hover {
opacity: 0.3;
}
.content {
margin-top: 50px;
font-size: 40px;
}
.content li:not(:first-of-type) {
display: none;
}
</style>
<body>
<div id="tab">
<ul class="btns">
<li>首頁</li>
<li>新聞</li>
<li>關(guān)于我們</li>
</ul>
<ul class="content">
<li>我是首頁內(nèi)容</li>
<li>我是新聞內(nèi)容</li>
<li>我是關(guān)于我們內(nèi)容</li>
</ul>
</div>
</body>
混合模式
function Tab(el){
//獲取到選項卡最大的容器
this.el=document.querySelector(el);
//獲取所有按鈕
this.btns= this.el.querySelector('.btns').children;
//獲取內(nèi)容
this.content = this.el.querySelector('.content').children;
}
Tab.prototype.init=function(){
var leng = this.btns.length;
var that = this;
for(var i=0;i<leng;i++){
this.btns[i].index=i;
this.btns[i].addEventListener('click',function(){
for(var j=0;j<leng;j++){
that.content[j].style.display='none';
}
that.content[this.index].style.display='block';
})
}
}
var tab = new Tab('#tab');
tab.init();
console.log(tab);
class定義對象(ES6語法扛或,推薦5獗)
- 優(yōu)點:
1、class 寫法更加簡潔艾恼、含義更加明確、代碼結(jié)構(gòu)更加清晰钠绍。
2、class 盡管也是函數(shù)五慈,卻無法直接調(diào)用。
3泻拦、class 不存在變量提升毙芜。
4、class 為污染 window 等全局變量腋粥。
5架曹、class 函數(shù)體中的代碼始終以嚴(yán)格模式執(zhí)行
class Tab{
init(){
var leng = this.btns.length;
//因為下面的點擊事件里的this會指向btns隘冲,所以要用that變量捕獲this绑雄,讓this指向?qū)嵗瘜ο? var that = this;
//循環(huán)第一次獲取到每個選項卡按鈕
for(var i = 0; i < leng; i++) {
//儲存btns的下標(biāo)值
this.btns[i].index = i;
//添加點擊事件
this.btns[i].addEventListener('click', function() {
//循環(huán)第二次獲取到每個選項卡內(nèi)容
for(var j = 0; j < leng; j++) {
//將所有內(nèi)容的display設(shè)置為none
that.content[j].style.display = 'none';
}
//根據(jù)上面獲取到選項卡按鈕下標(biāo)值顯示相應(yīng)的內(nèi)容
that.content[this.index].style.display = 'block';
})
}
}
}
class Tabchild extends Tab{
constructor(el){
super();
//獲取最大的盒子
this.el = document.querySelector(el);
//獲取按鈕万牺,.btns是按鈕的爸爸罗珍,加上.children就是指向按鈕
this.btns = this.el.querySelector('.btns').children;
//獲取內(nèi)容
this.content = this.el.querySelector('.content').children;
}
}
var tab = new Tabchild('#tab');
tab.init();