实现效果:
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notification 通知</title>
<style>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
.source{
display: flex;
margin-top: 50px;
margin-left: 50px;
width: 870px;
height: 80px;
padding: 24px;
border: 1px solid #ecf5ff;
}
button{
width: 110px;
height:40px;
margin-right: 20px;
color: #606266;
border: 1px solid #c0c4cc;
background-color: #fff;
border-radius: 3px;
}
button:hover{
border: 1px solid #409eff;
color:#409eff ;
}
button.active{
border: 1px solid #409eff;
color:#409eff ;
}
.modal-container {
position: fixed;
top: 20px;
right: 20px;
width: 330px;
}
.modal{
width: 330px;
border: 1px solid #c0c4cc;
padding: 14px 24px 14px 18px;
border-radius: 5px;
margin-bottom: 14px;
transform: translateX(350px);
transition: transform 0.3s ease-in-out;
}
.open{
transform: translateX(0);
}
.modal .header{
display: flex;
justify-content: space-between;
font-weight: 700;
font-size: 16px;
color: #303133;
padding-bottom: 5px;
}
i{
cursor: pointer;
font-style: normal;
font-weight: 300;
color: #606266;
}
.modal .footer{
color: #606266;
font-size: 14px;
}
</style>
</head>
<body>
<div class="source">
<button class="close">可自动关闭</button>
<button class="unclose">不会自动关闭</button>
</div>
<div class="modal-container">
<!-- 模态框将被动态添加到这个容器中 -->
<!-- <div class="modal">
<div class="header">标题名称<i>X</i></div>
<div class="footer">这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案</div>
</div> -->
</div>
<script>
// 1.Modal构造函数封装模态框
function Modal(title='',message=''){
// console.log(title,message);
// 创建modal模态框盒子
// 1.1创建div标签
this.modalBox=document.createElement('div')
// 1.2给div标签添加modal类
this.modalBox.className='modal'
// 1.3给modal盒子内部填充两个div标签
this.modalBox.innerHTML=`
<div class="header">${title} <i>X</i></div>
<div class="footer">${message} </div>
`
// console.log(this.modalBox);
}
new Modal('提示','这是一条不会自动关闭的消息')
// 2.给构造函数原型对象身上挂载open方法
Modal.prototype.open=function(){
document.querySelector('.modal-container').append(this.modalBox);
setTimeout(() => {
this.modalBox.classList.add('open');
}, 300);
// 点击关闭
this.closeBtn=this.modalBox.querySelector('.close-btn');
this.modalBox.querySelector('i').addEventListener('click', () => {
this.close();
});
}
// close方法
Modal.prototype.close=function(){
this.modalBox.classList.remove('open');
setTimeout(() => {
this.modalBox.remove();
}, 300); // 等待动画完成后移除元素
}
// 绑定点击事件
document.querySelector('.close').addEventListener('click', function() {
const modal = new Modal('标题名称','这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案这是提示文案');
modal.open();
// 设置模态框在3秒后自动关闭
setTimeout(() => {
modal.close();
}, 3000);
});
document.querySelector('.unclose').addEventListener('click',function(){
const unclose=new Modal('提示','这是一条不会自动关闭的消息')
unclose.open()
})
</script>
</body>
</html>