练习地址:http://www.fgm.cc/learn/lesson2/04.html
主要思路是:
按钮点击事件,设置弹出层的div的display为block显示,而且它的z-index危最大,让他覆盖在遮罩层上面。弹出层通过设置margin-top为负值使其上移到遮罩层来。
遮罩层跟弹出层是兄弟节点关系,宽高是100%,通过背景和opacity设置。
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>弹出层效果</title>
<link rel="stylesheet" type="text/css" href="4_popup.css">
</head>
<body>
<button>弹出层</button>
<div id="hide"></div>
<div id="popup">
<div id="title">
<div id="close">×</div>
</div>
<div id="content"></div>
</div>
<script type="text/javascript" src="4_popup.js"></script>
</body>
</html>
CSS
html, body, #hide {
width: 100%;
height: 100%;
margin: 0;
}
#hide {
display: none;
}
button {
position: absolute;
left: 640px;
top: 10px;
cursor: pointer;
}
#popup {
width: 400px;
height: 200px;
background: orange;
position: relative;
top: -450px;
margin: 0 auto;
padding: 5px;
z-index: 99;
display: none;
}
#title {
width: 400px;
height: 25px;
background: yellow;
margin: 0 auto;
}
#close {
color: orange;
background: white;
width: 13px;
height: 13px;
float: right;
margin: 5px 4px;
text-align: center;
line-height: 12px;
border: 1px solid orange;
cursor: pointer;
}
#content {
width: 400px;
height: 170px;
background: white;
margin-top: 5px;
}
JavaScript
window.onload = function() {
var btn = document.getElementsByTagName("button")[0];
var popup = document.getElementById("popup");
var close = document.getElementById("close");
var hide = document.getElementById("hide");
btn.onclick = function() {
popup.style.display = "block";
hide.style.display = "block";
hide.style.backgroundColor = "gray";
hide.style.opacity = "0.5";
}
close.onclick = function() {
popup.style.display = "none";
hide.style.display = "none";
}
}