半透明背景的彈出層非常適合用於登入、註冊或公告提示。本文示範一個做法:用兩個層,一個是鋪滿整個視窗的半透明遮罩,另一個是真正要顯示的置中內容方塊。完整程式碼如下:
復制代碼 代碼如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js+CSS彈出居中的背景半透明div層</title>
<style type="text/css">
body{margin:0px;}
#bg{width:100%; height:100%; top:0; left:0; position:absolute; filter:Alpha(opacity=50); opacity:0.5; background:#000000; display:none;}
#popbox{position:absolute; width:400px; height:400px; left:50%; top:50%; margin:-200px 0 0 -200px; display:none; background:#666666;}
</style>
<script type="text/javascript">
function pupopen(){
document.getElementById("bg").style.display="block";
document.getElementById("popbox").style.display="block";
}
function pupclose(){
document.getElementById("bg").style.display="none";
document.getElementById("popbox").style.display="none";
}
</script>
</head>
<body>
背景半透明風格的彈出層,在網站登入、用戶註冊、公告提示方面都非常適合使用。IE 和 FF、OP 均可。
原理:兩個層,一個高寬都是 100%,另一個是彈出視窗的具體內容;
半透明在 IE 中用 filter:Alpha(opacity=50),非 IE 中用 opacity:0.5。
<a href="#" onclick="pupopen()">點擊這裡打開窗口</a>
<div id="bg"></div>
<div id="popbox">這裡是彈出視窗的內容。<br><a href="#" onclick="pupclose()">點擊關閉窗口</a></div>
</body>
</html>
置中的關鍵是 left:50%; top:50% 搭配負的 margin(此例為 -200px),讓方塊中心對齊視窗中心;半透明則同時用 filter:Alpha 與 opacity 以相容各瀏覽器。點擊連結呼叫 pupopen 顯示、pupclose 隱藏即可。