浮層登入是常見需求,原理不難:一層半透明遮罩蓋住頁面,再把登入框置中疊上去。
<div id="shade"></div>
<div>
<a onclick="login()" style="cursor:pointer">登錄</a>
</div>
<div id="login" style="display:none; z-index:1025; position:absolute;">
<form method="post" action="user/login.html">
<table width="200">
<caption>用戶登錄</caption>
<tr>
<td>用戶名:</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>驗證碼:</td>
<td><img alt="" src="base/verify.html" /></td>
</tr>
<tr>
<td><input type="submit" value="登錄" /></td>
<td><input type="button" value="取消" onClick="cancel()" /></td>
</tr>
</table>
</form>
</div>
遮罩層要鋪滿可視範圍並半透明顯示:
#shade {
position: absolute;
top: 0; left: 0;
background: #000;
opacity: .5;
filter: alpha(opacity=50); /* 舊 IE */
display: none;
z-index: 1024;
}
function login() {
var shade = document.getElementById("shade");
shade.style.width = (document.body.clientWidth + 30) + "px";
shade.style.height = (document.body.clientHeight + 30) + "px";
shade.style.display = "block";
var loginDivWidth = 200, loginDivHeight = 800;
var loginDiv = document.getElementById("login");
loginDiv.style.width = loginDivWidth + "px";
loginDiv.style.height = loginDivHeight + "px";
loginDiv.style.top = (document.body.scrollTop
+ document.body.clientHeight / 2 - loginDivHeight / 2) + "px";
loginDiv.style.left = (document.body.scrollLeft
+ document.body.clientWidth / 2 - loginDivWidth / 2) + "px";
loginDiv.style.display = "block";
}
隱藏時,把 shade 與 login 兩個元素的 display 設回 none 即可。
原本作者嘗試在 onscroll / onresize / onload 裡重算座標,但實際效果不理想;網上找到的做法大多是設一個 setInterval 反覆重算,這並不理想——不但浪費效能,捲動時還容易出現殘影。
更穩定的思路是把置中計算抽成獨立函式,並改用 fixed 定位,讓浮層天生不受捲動影響:
function loginDivCenter() {
var w = 200, h = 800;
var el = document.getElementById("login");
el.style.position = "fixed";
el.style.top = ((window.innerHeight || document.documentElement.clientHeight) / 2 - h / 2) + "px";
el.style.left = ((window.innerWidth || document.documentElement.clientWidth) / 2 - w / 2) + "px";
}
window.onresize = loginDivCenter;
用 fixed 之後就不必靠計時器反覆重算座標,遮罩層本身也建議用 fixed 並搭配 height: 100% 鋪滿視窗。至於美工部分,就留給設計稿了。