javascript 弹出层(警告框)的制作(css元素居中、javascript元素居中)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>弹出层的制作</title>
</head>
<style type="text/css">
body {
padding: 0;
margin: 0;
}
#bg {
position: absolute;
width: 100%;
height: 100%;
background: blanchedalmond;
opacity: 0.5;
display: none;
}
p {
margin: 0 auto;
font-size: 30px;
background: #00FFFF;
width: 130px;
height: 50px;
cursor: pointer;
line-height: 50px;
text-align: center;
}
#win {
position: absolute;
top: 30%;
left: 50%;
width: 400px;
height: 200px;
background: #fff;
border: 4px solid #f90;
margin: -102px 0 0 -202px;
display: none;
}
h2 {
margin: 0;
width: 100%;
height: 50px;
background: skyblue;
}
#close {
float: right;
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
display: block;
cursor: pointer
}
</style>
<script type="text/javascript">
window.onload = function() {
var oBg = document.getElementById("bg");
var oBtn = document.getElementById("btn");
var oWin = document.getElementById("win");
var oClose = document.getElementById("close");
oBtn.onclick = function() {
oBg.style.display = "block";
oWin.style.display = "block";
}
oClose.onclick = function() {
oBg.style.display = "none";
oWin.style.display = "none";
}
}
</script>
<body>
<div id="bg"></div>
<div id="win">
<h2><span id="close">×</span></h2>
</div>
<p id="btn">弹出层</p>
</body>
</html>
CSS实现绝对定位元素的居中效果
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: 200px;
border: 4px solid #f90;
margin: -102px 0 0 -202px;
//宽高的一半
javascript实现元素的居中效果
居中的元素的top =(网页高 –元素的高)/ 2;
居中的元素的left= (网页宽 –元素的宽) /2;
转化为JavaScript的语法为:
top = (document.body.clientHeight - element.offsetHeight)/2;
left = (document.body.clientWidth - element.offsetWidth)/2