DIV CSS 佈局教程網

用 JS 製作頁面居中的彈出層 DIV 並顯示遮罩
編輯:關於JavaScript     

製作一個在頁面中央顯示、並帶半透明遮罩的彈出層,是常見的互動需求。以下示範如何實作,並特別處理了老舊 IE6 的相容問題。

CSS 樣式

*{margin:0;padding:0;}
.orderMsg{
  position:fixed;
  _position: absolute;
  _top: expression(documentElement.scrollTop + 340 + "px");
  background:#fff;
  border:1px solid #939395;
  width:500px; height:340px;
  top:50%; left:50%;
  margin:-200px 0 0 -250px;
  overflow:hidden;
  z-index:99999;
  display:none;
}

核心 JavaScript

var _CalF = {
  $     : function(id){ return document.getElementById(id); },
  create: function(id){ return document.createElement(id); },
  append: function(id){ return document.body.appendChild(id); },
  remove: function(id){ return document.body.removeChild(id); }
};

function popup(openID, conID, closeID){
  this.onclick(openID, conID, closeID);
}
popup.prototype = {
  cssStyle: "width:100%;position:absolute;left:0;top:0;filter:alpha(opacity=50);opacity:0.5;border:0;overflow:auto;",
  createShadowDiv: function(){ // 背景遮罩
    var shadowDiv = _CalF.create("div");
    shadowDiv.id = "shadowDiv";
    shadowDiv.style.cssText = this.cssStyle;
    shadowDiv.style.height = document.body.scrollHeight + "px";
    shadowDiv.style.backgroundColor = "#000";
    _CalF.append(shadowDiv);
  },
  createIframe: function(){ // 用 iframe 遮蓋 IE6 的 select
    var iframe = _CalF.create("iframe");
    iframe.id = "shadowIframe";
    iframe.style.cssText = this.cssStyle;
    iframe.style.height = document.body.scrollHeight + "px";
    _CalF.append(iframe);
  },
  removeDiv: function(){
    _CalF.remove(_CalF.$("shadowDiv"));
    _CalF.remove(_CalF.$("shadowIframe"));
  },
  onclick: function(openID, conID, closeID){
    var that = this;
    _CalF.$(openID).onclick = function(){
      if (window.ActiveXObject && !window.XMLHttpRequest) { // IE6
        document.body.style.cssText =
          "_background-image:url(about:blank);_background-attachment:fixed;";
      }
      that.createIframe();
      that.createShadowDiv();
      _CalF.$(conID).style.display = "block";
    };
    document.getElementById(closeID).onclick = function(){
      _CalF.$(conID).style.display = "none";
      that.removeDiv();
    };
  }
};
var bt = new popup("bt", "orderMsg", "close");

設計說明

這個彈出層的做法相當完整:用 position: fixed 搭配 top/left 50% 與負的 margin,讓彈出層精準置中;再動態建立一個半透明的遮罩 div 蓋住背景。特別值得一提的是它對 IE6 的兩處 hack——一是用 CSS expression 讓固定定位在 IE6 中模擬置中,二是插入一個 iframe 來遮蓋住 IE6 中會穿透遮罩的 select 元素(這是 IE6 著名的 z-index bug)。

已知限制

作者也誠實列出了目前="?"的限制:僅支援 id 選擇器、需自行設定彈出層的 CSS、IE6 下需額外設定,以及 IE6 中遮罩 div 無法呈現透明度等。儘管如此,這份程式碼把置中、遮罩、跨瀏覽器相容等關鍵環節都處理到了,是相當值得參考的完整範例。

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