功能:点击打开模态框按钮时显示模态框;点击关闭按钮时隐藏模态框;点击模态框外部时隐藏模态框 ;
原理:通过display:block;与display:none控制元素的显示与隐藏,实现模态框功能。
效果如下:
模态框操作视频
- 参考代码
<!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>Document</title>
<style>
.modal {
display: none; /* 初始是隐藏的 */
position: absolute;
z-index: 1;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
padding: 20px;
width: 80%;
border: 1px solid #888;
background-color: #fefefe;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<button id="openModal" >打开模态框</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>这是一个模态框</h2>
<p>这是模态框的内容。</p>
</div>
</div>
<script>
var modal = document.getElementById("modal"); // 获取模态框
var btn = document.getElementById("openModal"); // 获取打开按钮
var span = document.getElementsByClassName("close")[0]; // 获取关闭按钮
// 点击打开按钮时显示模态框
btn.onclick = function() {
modal.style.display = "block";
}
// 点击关闭按钮时隐藏模态框
span.onclick = function() {
modal.style.display = "none";
}
//点击模态框外部时隐藏模态框
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>