DIV CSS 佈局教程網

js 配合 CSS 實現居中且背景半透明的彈出層
編輯:JavaScript綜合知識     

登入框、註冊框、公告提示——這些場景都很適合用「半透明遮罩 + 居中彈窗」的組合。它的結構其實非常簡單:兩個層,一個鋪滿整個視窗作為遮罩,一個承載實際內容並水平垂直居中。

兩個核心技巧

遮罩的半透明。舊版 IE 認 filter: Alpha(opacity=50),其他瀏覽器認標準的 opacity: 0.5,兩句一起寫就能覆蓋絕大部分環境。

內容層的絕對居中。把彈窗設為 position:absolute; left:50%; top:50%,再用負的 margin 補回自身尺寸的一半:margin:-200px 0 0 -200px。寬高各 400px,所以四個方向都減去 200px,元素中心就精準落在視窗正中。

完整代碼

<!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:0px; left:0px;
  position:absolute; display:none;
  filter: Alpha(opacity=50);
  opacity:0.5;
  background:#000000;
}
#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>
<p>CSS 彈出層,或者說是彈出窗口,背景半透明風格的彈出框。</p>
<p>在網站登入、用戶註冊、公告提示方面都非常適合使用,IE、FF、Opera 均可。</p>
<p>原理:兩個層,一個高度和寬度都是 100%,另一個就是你要彈出的具體內容。</p>
<p>半透明在 IE 中寫 filter: Alpha(opacity=60);,非 IE 中寫 opacity:0.60;</p>
<a href="#" onclick="pupopen()">點擊這裡打開窗口</a>
<div id="bg"></div>
<div id="popbox">
  兩個層,一個高度和寬度都是 100%,另一個就是你要彈出的具體內容。
  <br><br><br>
  <a href="#" onclick="pupclose()">點擊關閉窗口</a>
</div>
</body>
</html>

可以再打磨的地方

· 把居中方式換成 position:fixed 搭配 transform: translate(-50%, -50%),就不必再手算負 margin,尺寸可變時也不用改 CSS。

· 用 fixed 定位還能解決一個老問題:頁面很長時,absolute 的遮罩不會跟著滾動,遮不住整屏。

· 遮罩層加上 onclick="pupclose()",讓用戶點擊空白處也能關閉,符合當下的交互習慣。

· 記得在彈窗打開時給 body 加上防止滾動的樣式,避免背景跟著滾動。

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