DIV CSS 佈局教程網

用原生 JavaScript 打造一個簡潔彈出視窗
編輯:關於JavaScript     

本文示範如何點擊按鈕後在頁面上彈出一個視窗,而原本的頁面內容保持不變,只是在其上覆蓋一層半透明的遮罩,讓焦點集中到彈窗上。彈窗既可以固定在畫面中央,也可以自由調整位置,這種做法在網站的登入框、提示框中非常常見。

實現步驟可以拆成三塊:先動態建立一個鋪滿整個頁面的遮罩層,再建立承載內容的彈窗容器,最後透過簡單的計算把彈窗置中顯示,並綁定關閉事件即可。

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-color: #ccc; } </style> </head> <body> <div id="menu"> <div id="login-area"> <button id="btnLogin">登錄</button> </div> </div> </body> </html> 

JavaScript 部分:

 <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> 

置中的關鍵在於「頁面寬度減去彈窗寬度再除以二」,垂直方向同理;同時點擊關閉按鈕或遮罩本身都能關閉彈窗,操作起來相當直覺。這段程式碼只用原生 API 即可完成,沒有任何依賴,很適合作為理解 DOM 動態操作的小練習。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved