单例模式:自定义弹框
Posted 乱舞春秋__
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式:自定义弹框相关的知识,希望对你有一定的参考价值。
功能
- 自定义弹框标题
- 自定义弹框内容
- 自定义弹框确认和关闭时的回调函数
完整代码
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: '标题',
confirmText: '确定',
cancelText: '取消'
}, res => { console.log(res) })
效果图
以上是关于单例模式:自定义弹框的主要内容,如果未能解决你的问题,请参考以下文章