一、初始页面
二、 点击按钮后
三、点击“×”后,效果与图一相同。
HTML代码:
<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>
<link rel="stylesheet" href="../清楚浏览器格式.css">
<link rel="stylesheet" href="./模态框.css">
</head>
<body>
<button class="btn">模态框</button>
<div class="box">
<div class="content">
<span id="closeBtn" class="close">×</span>
<h2>这是一个模态框!</h2>
</div>
</div>
</div>
</body>
CSS代码:
/* 按钮 */
button {
position: fixed;
left: 0;
top: 0;
z-index: -1;
}
/*模态框*/
.box {
position: relative;
display: none;
width: 100vw;
height: 100vh;
background-color: lightpink;
opacity: 80%;
align-items: center;
}
/*模态框内容*/
.content {
top: 35vh;
display: flex;
position: relative;
background-color: lightblue;
opacity: 1;
margin: auto;
padding: 20px;
width: 30vw;
height: 150px;
border-radius: 20px;
}
/*关闭按钮*/
.close {
position: relative;
top: -35px;
right: -390px;
text-align: center;
color: #aaa;
font-size: 28px;
font-weight: bold;
background-color: aliceblue;
display: inline-block;
width: 30px;
height: 30px;
line-height: 30px;
border-radius: 50%;
}
.close:hover {
color: black;
cursor: pointer;
}
h2 {
align-items: center;
height: 150px;
line-height: 150px;
}
JS代码:
<script>
let button = document.querySelector(".btn")
let closeBtn = document.querySelector(".close");
let box = document.querySelector(".box");
console.log(button, closeBtn, box);
// 点击按钮显示模态框
button.onclick = function () {
box.style.display = "block";
}
// 点击关闭按钮隐藏模态框
closeBtn.onclick = function () {
box.style.visibility = "hidden";
}
</script>