功能介紹:點擊一個按鈕,然后頁面會彈出一個窗口,而頁面原來的內容會保持不變,只是在其頁面上加了一個遮罩層,設置了不透明度,彈出的窗口可設置在固定位置,也可以自由設定,常見于網站的登錄按鈕。
html頁面:
<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>js實現一個彈出框</title><style type="text/css">/*預先寫好彈出窗的樣式*/#menu{height: 900px;}#close{   width:30px;   height:30px;   cursor:pointer;   position:absolute;   right:5px;   top:5px;   text-indent:-999em;  background-color:blue;  }#mask{   background-color:pink;  opacity:0.5;  filter: alpha(opacity=50);   position:absolute;   left:0;  top:0;  z-index:1;  }#login{   position:fixed;  z-index:2;  }.loginCon{   position:relative;   width:670px;  height:380px;  /*background:url(img/loginBg.png) #2A2C2E center center no-repeat;*/  background-color: #ccc;  }</style></head><body><div id="menu">  <div id="login-area">   <button id="btnLogin">登錄</button>  </div></div></body></html>js代碼:
<script>function openNew(){  //獲取頁面的高度和寬度  var sWidth=document.body.scrollWidth;  var sHeight=document.body.scrollHeight;    //獲取頁面的可視區域高度和寬度  var wHeight=document.documentElement.clientHeight;    var oMask=document.createElement("div");    oMask.id="mask";    oMask.style.height=sHeight+"px";    oMask.style.width=sWidth+"px";    document.body.appendChild(oMask);  var oLogin=document.createElement("div");    oLogin.id="login";    oLogin.innerHTML="<div class='loginCon'><div id='close'>關閉</div></div>";    document.body.appendChild(oLogin);    //獲取登陸框的寬和高  var dHeight=oLogin.offsetHeight;  var dWidth=oLogin.offsetWidth;    //設置登陸框的left和top    oLogin.style.left=sWidth/2-dWidth/2+"px";    oLogin.style.top=wHeight/2-dHeight/2+"px";  //點擊關閉按鈕  var oClose=document.getElementById("close");      //點擊登陸框以外的區域也可以關閉登陸框    oClose.onclick=oMask.onclick=function(){          document.body.removeChild(oLogin);          document.body.removeChild(oMask);          };          };            window.onload=function(){      var oBtn=document.getElementById("btnLogin");        //點擊登錄按鈕        oBtn.onclick=function(){          openNew();          return false;          }            }</script>新聞熱點
疑難解答