JavaScript实现弹出窗口
思路
- 总体使用两个div,一个作为底层展示,一个做为弹出窗口;
- 两个窗口独立进行CSS设计,通过display属性进行设置显示与隐藏,此处建议使用display属性而不是visibility属性,visibility:hidden可以隐藏某个元素,但隐藏的元素仍需占用与未隐藏之前一样的空间,影响布局;
- 在js内设计两个onclick事件,分别指定函数,分别为开启弹窗和关闭弹窗。
一、设置两个div
<html>
<title>弹出窗口</title>
<head>
<meta charset="UTF-8">
</head>
<body>
// 底层div
<div id="popLayer">
</div>
// 弹出层div
<div id="popDiv">
</div>
</body>
</html>
二、对两个div进行独立CSS设置,弹出窗口display设为none
<html>
<title>弹出窗口</title>
<head>
<meta charset="UTF-8">
<style type="text/css">
body{
background-color: cyan;
}
#popDiv{
display: none;
background-color: crimson;
z-index: 11;
width: 600px;
height: 600px;
position:fixed;
top:0;
right:0;
left:0;
bottom:0;
margin:auto;
}
</style>
</head>
<body>
// 底层div
<div id="popLayer">
<button onclick="">弹窗</button>
</div>
// 弹出层div
<div id="popDiv">
<div class="close">
// 关闭按钮超链接
<a href="" onclick="">关闭</a>
</div>
<p>此处为弹出窗口</p>
</div>
</body>
</html>
三、定义并设置弹出按钮和关闭窗口函数
<script type="text/javascript">
function popDiv(){
var popBox = document.getElementById("popDiv");
var popLayer = document.getElementById("popLayer");
popBox.style.display = "block";
popLayer.style.display = "block";
}
function closePop(){
let popDiv = document.getElementById("popDiv");
popDiv.style.display = "none";
}
</script>
四、将函数设置到onclick事件中
<button onclick="popDiv();">弹窗</button>
<a href="javascript:void(0)" onclick="closePop()">关闭</a>
五、设置关闭链接CSS和pop界面的其余CSS
<style type="text/css">
#popDiv .close a {
color: #2D2C3B;
}
#popDiv .close{
text-align: right;
margin-right: 5px;
background-color: #F8F8F8;
}
#popDiv p{
text-align: center;
font-size: 25px;
font-weight: bold;
}
</style>
六、整体代码
<html>
<title>弹出窗口</title>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function popDiv(){
var popBox = document.getElementById("popDiv");
var popLayer = document.getElementById("popLayer");
popBox.style.display = "block";
popLayer.style.display = "block";
}
function closePop(){
let popDiv = document.getElementById("popDiv");
popDiv.style.display = "none";
}
</script>
<style type="text/css">
body{
background-color: cyan;
}
#popDiv{
display: none;
background-color: crimson;
z-index: 11;
width: 600px;
height: 600px;
position:fixed;
top:0;
right:0;
left:0;
bottom:0;
margin:auto;
}
#popDiv .close a {
text-decoration: none;
color: #2D2C3B;
}
#popDiv .close{
text-align: right;
margin-right: 5px;
background-color: #F8F8F8;
}
#popDiv p{
text-align: center;
font-size: 25px;
font-weight: bold;
}
</style>
</head>
<body>
<div id="popLayer">
<button onclick="popDiv();">弹窗</button>
</div>
<div id="popDiv">
<div class="close">
<a href="javascript:void(0)" onclick="closePop()">关闭</a>
</div>
<p>此处为弹出窗口</p>
</div>
</body>
</html>