對于頁面中某些重復(fù)元素要設(shè)置相同或類似的動態(tài)屬性,為了盡量減少代碼重復(fù),我們可以利用JS面向?qū)ο蟮臉?gòu)造函數(shù)思想來封裝組件。
舉例:
頁面中兩個盒子,一個盒子通過鼠標點擊,可以切換顯示的內(nèi)容。另一個盒子自動切換顯示的內(nèi)容。

面向?qū)ο笏枷敕庋b組件 - 1.png

面向?qū)ο笏枷敕庋b組件 - 2.png
分析:
兩個盒子的共同點:
盒子的布局完全相同,子節(jié)點相同
切換顯示內(nèi)容的動態(tài)事件相同
兩個盒子的不同點:
觸發(fā)事件的方式不同,一個是點擊事件,一個是自動觸發(fā)(頁面加載)
思路:
我們通過一個構(gòu)造函數(shù),以盒子的id為參數(shù),構(gòu)造出一個實例對象,這個對象可以調(diào)用構(gòu)造函數(shù)上的方法來實現(xiàn)動態(tài)事件。
在構(gòu)造函數(shù)中,我們把兩個盒子的共同的屬性放到構(gòu)造函數(shù)的屬性里,將點擊事件和自動觸發(fā)事件分別作為兩個方法,放到構(gòu)造函數(shù)的原型 prototype 上。
實現(xiàn)代碼:
HTML 部分:
<div id="div1">
<p style="background-color: pink">點擊切換</p>
<button class="on">1</button>
<button>2</button>
<button>3</button>
<div style="display: block">哈哈哈哈哈</div>
<div>嘻嘻嘻嘻嘻</div>
<div>嘿嘿嘿嘿嘿</div>
</div>
<div id="div2">
<p style="background-color: pink">自動切換</p>
<button class="on">1</button>
<button>2</button>
<button>3</button>
<div style="display: block">哈哈哈哈哈</div>
<div>嘻嘻嘻嘻嘻</div>
<div>嘿嘿嘿嘿嘿</div>
</div>
CSS 部分:
<style>
#div1>div,
#div2>div{
border: 1px solid red;
width: 200px;
height: 200px;
display: none;
margin-bottom: 30px;
}
#div1 button,
#div2 button{
width: 50px;
height: 30px;
}
.on{
background-color: red;;
}
p{
width: 200px;
}
</style>
JS 部分:
function Change(id) {
this.box = document.querySelector(id);
this.btns = this.box.querySelectorAll('button');
this.divs = this.box.querySelectorAll('div');
this.num = 0;
// 改變按鈕樣式和下面的顯示內(nèi)容,是通用方法,放在屬性里
this.itemChange = (index)=> {
this.divs.forEach((item)=>{
item.style.display = 'none';
});
this.divs[index].style.display = 'block';
this.btns.forEach((item) => {
item.classList.remove('on');
});
this.btns[index].classList.add('on');
};
}
//點擊改變
Change.prototype.go = function () {
this.btns.forEach((item,index) => {
item.onclick = () =>{
this.itemChange(index)
}
});
};
// 自動改變,用定時器實現(xiàn)
Change.prototype.autogo = function(){
setInterval(()=>{
this.num ++;
if (this.num > this.btns.length - 1){this.num = 0}
this.itemChange(this.num);
}, 500)
};
// 生成盒子1的實例,調(diào)用相應(yīng)動態(tài)方法
let box1 = new Change('#div1');
box1.go();
// 生成盒子2的實例,調(diào)用相應(yīng)動態(tài)方法
let box2 = new Change('#div2');
box2.autogo();