帶有背景鎖屏遮罩的彈出層程式碼例項

antzone發表於2017-04-13

分享一段程式碼例項,它實現了點選按鈕彈出帶有遮罩層的視窗功能。

比較常見於使用者登入後者註冊之類的效果,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#btn {
  height: 50px;
  width: 150px;
  margin: 400px auto;
  font-size: 20px;
  background-color: grey;
  text-align: center;
  line-height: 50px;
}
#bg {
  background-color: silver;
  opacity: 0.75;
  position: absolute;
  left: 0;
  top: 0;
  height: 1000px;
  width: 100%;
  z-index: 2;
}
#login {
  width: 500px;
  height: 300px;
  background-color: greenyellow;
  z-index: 3;
  position: fixed;
}
.login-top {
  margin: 0;
  height: 50px;
  width: 500px;
  background-color: aqua;
}
#close {
  float: right;
  width: 40px;
  height: 50px;
  line-height: 50px;
  font-size: 25px;
  text-align: center;
  background-color: darkgoldenrod;
}
</style>
<script>
window.onload=function(){
  function show(){
    var btn=document.getElementById('btn');
    var sHeight=document.documentElement.scrollHeight;
    var sWidth=document.documentElement.scrollWidth;
 
     var cHeight=document.documentElement.clientHeight;
 
     var oMask=document.createElement('div');
     oMask.id='bg';
     oMask.style.height=sHeight+'px';
     oMask.style.width=sWidth+"px";
     document.body.appendChild(oMask);
 
     var loginbox=document.createElement('div');
     loginbox.id='login';
     loginbox.innerHTML = '<div class="login-top">'+
                          '<div id="close">×</div>'+
                          '</div><div class="login-mian"></div>';
     document.body.appendChild(loginbox);
 
     oheight=300;
     oWidth=500;
     loginLeft=(sWidth-oWidth)/2;
     loginHeight=(cHeight-oheight)/2;
 
     login=document.getElementById('login');
     login.style.left=loginLeft+'px';
     login.style.top=loginHeight+'px';
 
 
     function close(){
       document.body.removeChild(oMask);
       document.body.removeChild(login);
     }
     document.getElementById('close').onclick = close;
  }
  document.getElementById('btn').onclick=show;
}
</script>
</head>
<body>
<div id='btn'>檢視效果</div>
</body>
</html>

相關文章