DIV CSS 佈局教程網

用 JavaScript 實現點擊按鈕彈出居中透明浮動層
編輯:JavaScript綜合知識     

有一類非常常見的對話框效果:點擊按鈕後,整個頁面變灰,畫面中央彈出一個浮動層窗口。本文將帶大家實現這樣一個居中顯示、可設置透明度的浮動層對話框,並附上完整的 CSS 與 JavaScript 代碼。

效果說明

點擊「演示」按鈕後,一個帶半透明灰色背景的浮動層會出現在頁面中央,其中包含標題與內容。這個對話框透過封裝成 NeatDialog 構造函數,讓調用變得非常簡潔,並提供關閉方法,方便重複使用。

核心代碼

<style>
DIV.neat-dialog-cont { Z-INDEX:98; LEFT:0px; WIDTH:100%; POSITION:absolute; TOP:0px; HEIGHT:100%; }
DIV.neat-dialog-bg { Z-INDEX:-1; FILTER:alpha(opacity=70); LEFT:0px; WIDTH:100%; POSITION:absolute; TOP:0px; HEIGHT:100%; BACKGROUND-COLOR:#eee; opacity:0.7; }
DIV.neat-dialog { BORDER:#555 1px solid; Z-INDEX:99; MARGIN-LEFT:auto; WIDTH:30%; MARGIN-RIGHT:auto; POSITION:relative; TOP:25%; BACKGROUND-COLOR:#fff; }
DIV.neat-dialog-title { PADDING:0.1em 0.3em; BORDER-BOTTOM:#444 1px solid; }
</style>
<script>
function NeatDialog(sHTML, sTitle, bCancel){
window.neatDialog = null;
this.elt = null;
if(document.createElement && document.getElementById){
var dg = document.createElement("div");
dg.className = "neat-dialog";
if(sTitle) sHTML = '<div class="neat-dialog-title">'+sTitle+'</div>' + sHTML;
dg.innerHTML = sHTML;
var dbg = document.createElement("div");
dbg.id = "nd-bdg";
dbg.className = "neat-dialog-bg";
var dgc = document.createElement("div");
dgc.className = "neat-dialog-cont";
dgc.appendChild(dbg);
dgc.appendChild(dg);
document.body.appendChild(dgc);
this.elt = dgc;
window.neatDialog = this;
}
}
NeatDialog.prototype.close = function(){
if(this.elt){
this.elt.parentNode.removeChild(this.elt);
}
window.neatDialog = null;
}
function openDialog(){
var sHTML = '<p>這是一個由 JS 控制彈出的層窗口</p>' +
'<p><button onclick="window.neatDialog.close()">關閉</button></p>';
new NeatDialog(sHTML, "你知道嗎?", false);
}
</script>
<button onclick="openDialog()">點此演示效果</button>

實現要點

整個對話框由三層結構組成:最外層 neat-dialog-cont 撐滿全屏作為容器;中間的 neat-dialog-bg 是半透明遮罩,透過 opacity 與 filter 兼顧各瀏覽器;最內層 neat-dialog 則是真正的內容窗口,透過 margin:auto 實現水平居中。把這些邏輯封裝進構造函數後,只需一行 new NeatDialog(...) 即可彈出對話框,非常利於復用。

希望本文所述能對大家的 JavaScript 程序設計有所幫助。

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