組件 :
?????方便復(fù)用,特別是一些復(fù)用率高的功能。
? ? 思路 : 通過傳入大的父級,就可以調(diào)用選項(xiàng)卡
步驟:
????1.先確定可配置項(xiàng):
? ??????寬 :width
????????高 :height
????????取消觸發(fā)函數(shù) : cancelFn
????????是否拖拽 :isDrag
????????內(nèi)容:content
????2.新建一個(gè)類
? ? ? ? ?(1)constructor里建變量,opt是配置項(xiàng)
? ? ? ? ?(2)使用Object.assign(),用配置項(xiàng)覆蓋默認(rèn)opt
? ? ? ? ?(3)調(diào)用init(初始化代碼,也就是基礎(chǔ)邏輯在這個(gè)方法里面)? ??
? ? ? ? (4)將功能模塊拆分财松,仔細(xì)分析實(shí)現(xiàn)這個(gè)需求需要的功能梆掸,一個(gè)功能寫一個(gè)方法扬卷,降低耦合。
? ? ? ? (5)在init中調(diào)用各方法
class Tab{
//1
? ? constructor(obj){
this.opt= {
obj: null,
? ? ? ? ? ? btns: ['新聞','體育','娛樂','社會'],
? ? ? ? ? ? contents: ['十八大召開','科比退役','鄭爽','房價(jià)下跌'],
? ? ? ? ? ? width: 200,
? ? ? ? ? ? height: 150,
? ? ? ? ? ? isDrag: false
? ? ? ? }
//2.右值賦給左值:如果有配置酸钦,就會覆蓋opt,如果沒有配置怪得,就運(yùn)行opt中的參數(shù)
? ? ? ? Object.assign(this.opt,obj)
this.box= document.querySelector(this.opt.obj)
this.init()
}
//2
? ? init(){//初始化
? ? ? ? this.creatBtns()
this.creatDiv()
this.events()
this.boxStyle()
//是否調(diào)用拖拽
? ? ? ? /*if(this.isDrag){
new Drag()
}*/
? ? }
//3
? ? creatBtns(){
let html= ''
? ? ? ? this.opt.btns.forEach((el,i)=>{
html+=`${el}`
? ? ? ? })
this.box.innerHTML= html
}
creatDiv(){
let html= ''
? ? ? ? this.opt.contents.forEach((c,i)=>{
html+=`
${c}
`
? ? ? ? })
this.box.innerHTML+= html
}
events(){
this.btns= Array.from(document.querySelectorAll('button'))
this.divs= this.box.querySelectorAll('div')
let that= this
? ? ? ? this.btns.forEach((e,i)=>{
e.onclick = function(){
that.change(i)
}
})
}
change(index){
this.btns.forEach((e,i)=>{
e.className= ''
? ? ? ? ? ? this.divs[i].className=''
? ? ? ? })
this.btns[index].className= 'active'
? ? ? ? this.divs[index].className= 'show'
? ? }
boxStyle(){
this.box.style.cssText=`width:${this.opt.width}px;height:${this.opt.height}px`
? ? }
}
let t = new Tab({
obj: '#box',
? ? width: '500'
})