這次沿用原本的程式碼組織結構,重新加強了功能。目前還有兩個已知的小問題:
第一,IE6 下自訂的彈出層無法遮住 select 元素。這暫時還沒整合進元件中,你可以在自訂的 div 裡自己加上 iframe 來做遮罩;元件自帶的彈出層則不受影響。
第二,因為採用絕對定位,改變瀏覽器視窗大小時不會自動跟隨。這兩個是我認為比較重要的問題,暫時先列出來,之後再修。
線上展示:https://demo.jb51.net/js/2011/js_popup_up/index.htm
以下程式碼都附有註解,可直接執行:
<!DOCTYPE>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>lock page</title>
<link rel="stylesheet" type="text/css" href="style/css/j_dialog.css" />
<style>
body {padding:0; margin:0; font: 12px/1.5 Tahoma, Helvetica, Arial, sans-serif;}
body, h1, h2, h3, h4, h5, h6, hr, p, blockquote, dl, dt, dd, ul, ol, li,
pre, form, fieldset, legend, button, input, textarea, th, td {margin: 0; padding: 0;}
button, input, select, textarea {font: 12px/1.5 tahoma, arial, simsun, sans-serif;}
h1, h2, h3, h4, h5, h6 {font-size: 100%; font-weight: normal;}
address, cite, dfn, em, var {font-style: normal;}
code, kbd, pre, samp {font-family: courier new, courier, monospace;}
small {font-size: 12px;}
ul, ol {list-style: none;}
sup {vertical-align: text-top;}
sub {vertical-align: text-bottom;}
legend {color: #000;}
fieldset, img {border: 0;}
table {border-collapse: collapse; border-spacing: 0;}
.clear {clear: both;}
html {overflow: -moz-scrollbars-vertical;}
a {text-decoration: none;}
a:hover {text-decoration: underline;}
#pageOverlay {overflow:hidden; display:none; position:fixed; top:0; left:0;
z-index:1987; width:100%; height:100%; background:#000;
filter:alpha(opacity=70); opacity:0.7;}
.pageDialog {border: 4px solid #999999; display:none; position:fixed;
top:40%; left:50%; z-index:1988; background:#fff;}
.pageDialog h3 {padding-left:10px; overflow:hidden; font-size:14px; font-weight:normal;
height:25px; line-height:25px; background:#666; color:#fff; zoom:1;}
.pageDialog h3 a {float:right; color:#ddd; display:inline; font-weight:bold;
width:20px; text-align:center; margin-right:5px;}
.pageDialog h3 a:hover {text-decoration: none; color:#fff;}
.pageDialog span {margin:10px; display: block;}
.pageDialog .confirm, .pageDialog .concel {display:inline-block;
background:#ccc url(../images/DialogBtn.png) no-repeat; width:45px; height:25px;
text-align:center; line-height:25px; font-weight:bold; margin-right:10px;}
.pageDialog .confirm:hover, .pageDialog .concel:hover {text-decoration: none;}
.pageDialog .confirm {background-position:0 0; color:#000;}
.pageDialog .concel {background-position:-45px 1px; color:#000; display:none;}
.oprate {margin:20px 0 10px 0; text-align:center;}
#test li {display:inline;}
</style>
<script type="text/javascript">
function d_log(contents) {
if (!(this instanceof d_log))
return new d_log(contents);
this.title = contents && contents.title || "系統提示"; // 預設系統提示
this.con = contents && contents.con || ""; // 預設彈出內容為空
this.wrap = contents && contents.wrapId; // 是否為自訂彈出層
this.confirm = contents && contents.confirm; // 是否需要確認按鈕
this.wraphide= contents && contents.wraphide || !1; // 是否顯示背景遮罩
this.pos = contents && contents.pos; // 自帶四角定位
if (document.getElementById('pageOverlay')) {
// 共用一個遮罩層,避免冗余標籤
this.cover = document.getElementById('pageOverlay');
} else {
this.cover = document.createElement('div');
this.cover.id = 'pageOverlay';
this.cover.style.display = 'none';
document.body.appendChild(this.cover);
}
this.dialog = document.createElement('div');
this.dialog.className = 'pageDialog';
document.body.appendChild(this.dialog);
this.init();
}
d_log.prototype.init = function () {
var self = this, c_height, l, t;
c_height = document.compatMode != "BackCompat"
? document.documentElement.clientHeight
: document.body.clientHeight;
if (self.wrap) {
// 有指定顯示的層,把它加入彈出層
self.dialog.appendChild(document.getElementById(self.wrap));
} else {
// 沒有則重新建構一個彈出層
self.dialog.innerHTML = '<div style="width:300px;"><h3>'
+ '<a class="d_dialog_close" href="javascript:;">x</a>' + self.title + '</h3>';
self.dialog.innerHTML += self.con
+ "<p class='oprate'><a href='javascript:;' class='confirm'>確定</a>"
+ "<a href='javascript:;' class='concel'>取消</a></p></div>";
var _p = self.dialog.getElementsByTagName('p')[0];
if (self.confirm)
_p.lastChild.style.display = 'inline-block';
addEvent(_p.getElementsByTagName('a')[0], 'click', function () {
self.close();
if (self.confirm) eval(self.confirm + '()');
});
addEvent(_p.getElementsByTagName('a')[1], 'click', function () { self.close(); });
addEvent(self.dialog.getElementsByTagName('a')[0], 'click', function () { self.close(); });
}
// 依 pos 參數決定位置
switch (self.pos) {
case 'left-top':
l = 0; t = 0; break;
case 'left-bottom':
l = 0; t = c_height - parseInt(getSize(self.dialog).height); break;
case 'right-top':
l = document.body.clientWidth - parseInt(getSize(self.dialog).width); t = 0; break;
case 'right-bottom':
l = document.body.clientWidth - parseInt(getSize(self.dialog).width);
t = c_height - parseInt(getSize(self.dialog).height); break;
default: // 置中
l = (document.body.clientWidth - parseInt(getSize(self.dialog).width)) / 2;
t = (c_height - parseInt(getSize(self.dialog).height)) / 2;
}
self.dialog.style.left = l + 'px';
self.dialog.style.top = t + 'px';
// IE6 專用處理:position:fixed 在 IE6 無效,需用 absolute + expression 模擬
if (!window.XMLHttpRequest) {
var body, clone, cover = self.cover;
var iframe = '<iframe width="100%" height="100%" frameborder="0" scrolling="no"'
+ ' style="z-index:1000; position: absolute; left: 0pt; top: 0pt;'
+ ' filter:alpha(opacity=0);"></iframe>';
self.dialog.style.position = 'absolute';
try { document.execCommand("BackgroundImageCache", false, true); } catch (e) {}
(function () {
body = document.body;
if (body.currentStyle.backgroundAttachment !== "fixed") {
if (body.parentNode.currentStyle.backgroundImage === "none") {
body.parentNode.runtimeStyle.backgroundRepeat = "no-repeat";
body.parentNode.runtimeStyle.backgroundImage = "url(about:blank)";
}
body.style.height = '100%';
}
self.layer = document.createElement(
"<div style='position:absolute;z-index:1990;border:0;padding:0;margin:0;"
+ "overflow:hidden;background:transparent;"
+ "top:expression((document).documentElement.scrollTop);"
+ "left:expression((document).documentElement.scrollLeft);"
+ "width:expression((document).documentElement.clientWidth);"
+ "height:expression((document).documentElement.clientHeight);display:none;'>");
})();
clone = self.dialog.cloneNode(true);
document.body.removeChild(self.dialog);
self.layer.appendChild(clone);
self.dialog = clone;
if (self.layer.parentNode !== body)
body.insertBefore(self.layer, body.childNodes[0]);
cover.innerHTML = iframe;
cover.style.cssText = 'position:absolute;'
+ 'left:expression((document).documentElement.scrollLeft);'
+ 'top:expression((document).documentElement.scrollTop);'
+ 'width:expression((document).documentElement.clientWidth);'
+ 'height:expression((document).documentElement.clientHeight);';
}
}
d_log.prototype.open = function () {
if (this.layer) this.layer.style.display = 'block';
this.dialog.style.display = 'block';
if (!this.wraphide) this.cover.style.display = 'block';
}
d_log.prototype.close = function () {
if (this.layer) this.layer.style.display = 'none';
this.dialog.style.display = 'none';
this.cover.style.display = 'none';
}
// 取得元素寬高,包含隱藏元素
function getSize(elem) {
var width = elem.offsetWidth, height = elem.offsetHeight;
if (!width && !height) {
var style = elem.style;
var cssShow = "position:absolute;visibility:hidden;display:block;left:-9999px;top:-9999px;";
var cssBack = "position:" + style.position + ";visibility:" + style.visibility
+ ";display:" + style.display + ";left:" + style.left + ";top:" + style.top;
elem.style.cssText = cssShow;
width = elem.offsetWidth; height = elem.offsetHeight;
elem.style.cssText = cssBack;
}
return { "width": width, "height": height };
}
// 綁定事件
function addEvent(el, type, fn) {
if (el.attachEvent) {
el['e' + type + fn] = fn; // IE下拷貝元素引用,使 this 指向 el 而非 window
el[type + fn] = function () { el['e' + type + fn](window.event); };
el.attachEvent('on' + type, el[type + fn]);
} else {
el.addEventListener(type, fn, false);
}
}
</script>
</head>
<body onload="dlg3.open()">
<ol id="test">
<li id="par" style="display:none;">
<a id='no1' class="abc ggl" href="javascript:dlg1.open();">點擊我試試</a></li>
<li><a href="javascript:dlg2.open();">自訂彈出層</a></li>
<li><a href="javascript:dlg1.open();">自帶模態對話框</a></li>
<li><a href="javascript:dlg3.open();">右下角廣告</a></li>
</ol>
<div id="result"></div>
<select><option label="1111111111">abcd111</option>
<option label="222222222">abcd222</option></select>
<div id="owp" style="width:300px;height:200px;">
這是第二個測試例子!<a href="javascript:dlg2.close();">x</a></div>
<div id="owp1" style="width:200px;height:100px;">
右下角廣告<a href="javascript:dlg3.close();">x</a></div>
</body>
</html>
<script>
// 參數說明:
// con 自帶彈出框的內容
// confirm 是否需要確認按鈕(傳入函式名稱)
// wraphide 是否顯示遮罩層
// wrapId 自訂層的 id
// pos 彈出層的位置
var dlg1 = d_log({con:'<span>確定要刪除此檔案嗎?</span>', confirm:'check'});
var dlg2 = d_log({wraphide:'hide', wrapId:'owp'});
var dlg3 = d_log({wraphide:'hide', wrapId:'owp1', pos:'right-bottom'});
function check() {
alert('test!');
}
</script>
可省略 new 的建構方式:開頭的 if (!(this instanceof d_log)) return new d_log(contents); 讓呼叫端可以直接寫 d_log({...}) 而不必寫 new d_log({...}),是個常見的小貼心設計。
共用遮罩層:建立實例時會先檢查頁面上是否已有 pageOverlay,有的話就重複使用。這樣同頁面開啟多個彈出層時,不會堆疊出一堆一模一樣的遮罩 div。
兩種內容模式:傳入 wrapId 時,元件把該元素直接搬進彈出層中(適合自訂 UI);沒傳則由元件自行組出標題列與按鈕區(適合簡單確認框)。
IE6 的 position:fixed 補救:這段是最繁瑣的部分。IE6 不支援 position:fixed,只能用 absolute 搭配 CSS expression 動態計算座標來模擬。程式碼用 !window.XMLHttpRequest 來判斷是否為IE6(IE6不支援這個原生物件),命中時就進入這條相容分支,把 dialog 包進一個額外的 layer 裡,並在遮罩中插入透明 iframe 處理層級問題。
getSize 的隱藏元素處理:彈出層初始狀態是 display:none,此時 offsetWidth/offsetHeight 都會是0,無從計算置中位置。解法是暫時套用一組「移出視窗外但仍參與排版」的樣式強迫瀏覽器計算,讀完尺寸後再還原原本的 inline style。
若要在今天重寫這個元件,有幾個方向值得考慮:用 position:fixed 取代 expression(IE6 已無需支援);用 CSS transition 做進出動畫;把 eval(self.confirm + '()') 改成直接接受函式參照,避免 eval 帶來的風險與除錯困難;替 dialog 加上 role="dialog" 與 aria-modal="true",並實作焦點鎖定(focus trap)與 ESC 關閉,讓鍵盤使用者與螢幕閱讀器也能正常操作;最後,監聽 resize 事件重新計算位置,就能解掉視窗縮放時不跟隨的問題。