通过构造函数原型对象原理封装一个点击button按钮弹出信息提示框的函数
源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>面向对象封装消息提示</title>
<style>
.modal {
width: 300px;
min-height: 100px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
border-radius: 4px;
position: fixed;
z-index: 999;
left: 50%;
top: 50%;
transform: translate3d(-50%, -50%, 0);
background-color: #fff;
}
.modal .header {
line-height: 40px;
padding: 0 10px;
position: relative;
font-size: 20px;
}
.modal .header i {
font-style: normal;
color: #999;
position: absolute;
right: 15px;
top: -2px;
cursor: pointer;
}
.modal .body {
text-align: center;
padding: 10px;
}
.modal .footer {
display: flex;
justify-content: flex-end;
padding: 10px;
}
.modal .footer a {
padding: 3px 8px;
background: #ccc;
text-decoration: none;
color: #fff;
border-radius: 2px;
margin-right: 10px;
font-size: 14px;
}
.modal .footer a.submit {
background-color: #369;
}
</style>
</head>
<body>
<button id="delete">删除</button>
<button id="login">登录</button>
<!-- <div class="modal">
<div class="header">温馨提示 <i>x</i></div>
<div class="body">您没有删除权限操作</div>
</div> -->
<script>
// 构造函数
function Modal(head,message){
this.head = head
this.message = message
// 创建dom元素
this.modalBox = document.createElement('div')
// 添加类名
this.modalBox.classList.add('modal')
// 写入内容
this.modalBox.innerHTML = `
<div class="modal">
<div class="header">${this.head} <i>x</i></div>
<div class="body">${this.message}</div>
</div>
`
}
Modal.prototype.open =function (){
// 判断是否已存在modal类名的盒子 如果存在则点击不生效 (解决点击按钮重复生成盒子的bug)
if(!document.querySelector('.modal')){
// 原型对象内的this值就是new出来的实例化对象
document.body.appendChild(this.modalBox)
// i标签的点击事件必须写在原型对象的方法open内 因为只有open方法触发 i标签才被生成
document.querySelector('.header i').addEventListener('click', () =>{
// 函数必须使用箭头函数(没有this值 会往上找this值作为自己的this) 这样this值就能绑定在m1上
this.close()
})
}
}
Modal.prototype.close =function (){
// 构造函数内的this值就是new出来的实例化对象
document.body.removeChild(this.modalBox)
}
document.querySelector('#delete').addEventListener('click',() => {
// 创建实例化对象
const m1 = new Modal('温馨提示','您暂无权限')
// 调用原型对象上的方法
m1.open()
})
document.querySelector('#login').addEventListener('click',() => {
// 创建实例化对象
const m1 = new Modal('温馨提示','您还未注册账户')
// 调用原型对象上的方法
m1.open()
})
</script>
</body>
</html>