效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fc6f0fdd62bf7d43b456127423518e30.png)
function llAlert(args){
var zhezhao = document.createElement('div');
zhezhao.className = "zhezhao";
zhezhao.innerHTML = `
<div class="alert">
<div class="header"><span class="title">`+args.title+`</span><span class="close">X</span></div>
<div class="main">
`+args.content+`
</div>
<div class="btnList">
<div class="btn yes">确定</div>
<div class="btn no">取消</div>
</div>
</div>
`
var body = document.querySelector('body');
body.appendChild(zhezhao);
var closeDiv = document.querySelector(".close");
closeDiv.onclick = function(){
body.removeChild(zhezhao);
}
var yesDiv = document.querySelector(".btn.yes");
yesDiv.onclick = function(){
if(args.confirmFn() == 'function'){
args.confirmFn();
}else{
console.error("函数没有设置参数");
}
body.removeChild(zhezhao);
}
var noDiv = document.querySelector(".btn.no");
noDiv.onclick = function(){
if(typeof args.cancelFn() == 'function'){
args.cancelFn();
}else{
console.error("函数没有设置参数");
}
body.removeChild(zhezhao);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/alert.js" type="text/javascript" charset="UTF-8"></script>
</head>
<body>
<button type="button">是否跳转到百度页面</button>
<script type="text/javascript">
var button = document.querySelector("button");
button.onclick = function(){
llAlert({
title:"警告!",
content:"是否跳转百度页面",
confirmFn:function(){
location.href = "https://www.bilibili.com/";
},
cancelFn:function(){
var h1 = document.createElement("h1");
h1.innerHTML = "用户已取消跳转页面";
document.body.appendChild(h1);
}
})
}
</script>
</body>
</html>
*{
margin : 0;
padding: 0;
box-sizing: border-box;
}
.zhezhao{
position: fixed;
left: 0;
top: 0;
height: 100vh;
width: 100vw;
background-color: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
}
.alert{
width: 600px;
height: 400px;
background-color: #fff;
display: flex;
flex-direction: column;
}
.alert>.header{
height: 80px;
line-height: 80px;
border-bottom: 1px solid #ccc;
display: flex;
justify-content: space-between;
padding:0px 30px;
}
.alert>.header>.title{
font-size: 30px;
font-weight: 900;
color: #ccc;
}
.alert>.header>.close:hover{
color: red;
}
.alert>.main{
flex: 1;
padding:30px;
border-bottom: 1px solid #ccc;
}
.alert>.btnList{
height:80px;
display: flex;
justify-content: center;
align-items: center;
padding:0 30px;
}
.alert>.btnList>.btn{
height: 60px;
width:120px;
text-align: center;
line-height: 60px;
margin: 50px;
}
.alert>.btnList>.btn:nth-child(1){
background-color: coral;
}
.alert>.btnList>.btn:nth-child(2){
background-color: #999;
}