您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“如何使用JavaScript單例模式實(shí)現(xiàn)自定義彈框”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何使用JavaScript單例模式實(shí)現(xiàn)自定義彈框”這篇文章吧。
自定義彈框標(biāo)題
自定義彈框內(nèi)容
自定義彈框確認(rèn)和關(guān)閉時(shí)的回調(diào)函數(shù)
const Dialog = (function () { class Dialog { constructor () { this.ele = document.createElement('div') this.ele.className = 'dialog' document.body.appendChild(this.ele) this.callback = null this.setEvent() } setContent ({ text, topicText, confirmText, cancelText } = options) { this.ele.innerHTML = null const top = document.createElement('div') top.className = 'top' const topic = document.createElement('span') topic.className = 'topic' topic.innerHTML = topicText const close = document.createElement('span') close.className = 'close' close.innerHTML = '×' top.appendChild(topic) top.appendChild(close) const middle = document.createElement('div') middle.className = 'middle' const content = document.createElement('div') content.className = 'content' content.innerHTML = text middle.appendChild(content) const bottom = document.createElement('div') bottom.className = 'bottom' const confirm = document.createElement('button') confirm.className = 'confirm' confirm.innerHTML = confirmText const cancel = document.createElement('button') cancel.className = 'cancel' cancel.innerHTML = cancelText bottom.appendChild(confirm) bottom.appendChild(cancel) const wrap = document.createElement('div') this.ele.appendChild(top) this.ele.appendChild(middle) this.ele.appendChild(bottom) this.ele.style.display = 'block' } setEvent () { this.ele.addEventListener('click', e => { e = e || window.event const target = e.target || e.srcElement if (target.className === 'close') { this.ele.style.display = 'none' console.log('close') } if (target.className === 'confirm') { this.ele.style.display = 'none' this.callback(true) } if (target.className === 'cancel') { this.ele.style.display = 'none' this.callback(false) } }) } } let instance = null return function (options, cb) { if (!instance) instance = new Dialog() instance.setContent(options) instance.callback = cb || function () {} return instance } })() const dialog = new Dialog({ text: '提示文字', topicText: '標(biāo)題', confirmText: '確定', cancelText: '取消' }, res => { console.log(res) })
效果圖
以上是“如何使用JavaScript單例模式實(shí)現(xiàn)自定義彈框”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。