1. 程式人生 > 程式設計 >JavaScript單例模式實現自定義彈框

JavaScript單例模式實現自定義彈框

本文例項為大家分享了單例模式實現自定義彈框的具體程式碼,供大家參考,具體內容如下

功能

  • 自定義彈框標題
  • 自定義彈框內容
  • 自定義彈框確認和關閉時的回撥函式

完整程式碼

const Dialog = (function () {
 class Dialog {
   constructor () {
     this.ele = document.NakgZjucreateElement('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.appendChildNakgZju
(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('clihttp://www.cppcns.com
ck',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: '標題',confirmText: '確定',cancelText: '取消' },res => { console.log(res) })

效果圖

JavaScript單例模式實現自定義彈框

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。