案例 - 自定义弹出层
+ 约定
1. 提示: skyblue, info
2. 警告: yellow, warning
3. 危险: red, danger
4. 成功: green, success
js
// 以单例模式书写 自定义 弹出层
const Dialog = (function () {
// 类 本身
class Dialog {
constructor () {
// 1. 创建一个 div 标签
this.box = document.createElement('div')
// 添加类名
this.box.className = 'dialog'
// 插入页面
document.body.appendChild(this.box)
// 2. 设置 div 的结构样式和内容
this.setHtml('skyblue', '我是默认文本内容', '提示')
// 3. 事件绑定
this.setEvent()
}
setHtml (color, text, info) {
this.box.innerHTML = `
<div class="top" style="background-color: ${ color }">${ info }
<span>X</span>
</div>
<div class="content">
${ text }
</div>
<div class="bottom" style="background-color: ${ color }"></div>
`
// 可以在页面上出现了
this.box.style.display = 'flex'
}
setEvent () {
this.box.addEventListener('click', e => {
e = e || widnow.event
const target = e.target || e.srcElement
if (target.nodeName === 'SPAN') {
this.box.style.display = 'none'
}
})
}
}
// 单例模式核心代码
let instance = null
return function (text, color) {
if (!instance) instance = new Dialog()
// 通过 switch 来判断 color 单词, 我们来添加一个颜色进去
switch (color) {
case 'danger':
instance.setHtml('red', text, '危险')
break
case 'success':
instance.setHtml('green', text, '成功')
break
case 'warning':
instance.setHtml('yellow', text, '警告')
break
default:
instance.setHtml('skyblue', text, '提示')
}
return instance
}
})()
// 第一次使用的时候
// const d1 = new Dialog('登录成功', 'success')
// const d2 = new Dialog('登录失败', 'danger')
css
div.dialog {
width: 400px;
height: 230px;
display: flex;
flex-direction: column;
border: 1px solid #333;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
display: none;
}
.dialog > .top,
.dialog > .bottom {
width: 100%;
height: 40px;
background-color: skyblue;
box-sizing: border-box;
line-height: 40px;
padding-left: 20px;
position: relative;
}
.dialog > .top > span {
cursor: pointer;
position: absolute;
top: 50%;
transform: translateY(-50%);
right: 30px;
}
.dialog > .content {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}