千家信息网

如何使用JavaScript单例模式实现自定义弹框

发表于:2025-11-07 作者:千家信息网编辑
千家信息网最后更新 2025年11月07日,这篇文章主要为大家展示了"如何使用JavaScript单例模式实现自定义弹框",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"如何使用JavaScript单例
千家信息网最后更新 2025年11月07日如何使用JavaScript单例模式实现自定义弹框

这篇文章主要为大家展示了"如何使用JavaScript单例模式实现自定义弹框",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"如何使用JavaScript单例模式实现自定义弹框"这篇文章吧。

功能

  • 自定义弹框标题

  • 自定义弹框内容

  • 自定义弹框确认和关闭时的回调函数

完整代码

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[xss_clean] = null     const top = document.createElement('div')     top.className = 'top'     const topic = document.createElement('span')     topic.className = 'topic'     topic[xss_clean] = topicText     const close = document.createElement('span')     close.className = 'close'     close[xss_clean] = '×'     top.appendChild(topic)     top.appendChild(close)     const middle = document.createElement('div')     middle.className = 'middle'     const content = document.createElement('div')     content.className = 'content'     content[xss_clean] = text     middle.appendChild(content)     const bottom = document.createElement('div')     bottom.className = 'bottom'     const confirm = document.createElement('button')     confirm.className = 'confirm'     confirm[xss_clean] = confirmText     const cancel = document.createElement('button')     cancel.className = 'cancel'     cancel[xss_clean] = 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: '标题', confirmText: '确定', cancelText: '取消' }, res => { console.log(res) })

效果图

以上是"如何使用JavaScript单例模式实现自定义弹框"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

0