DIV CSS 佈局教程網

以 jQuery 框架撰寫的彈窗效果(適合新手)
編輯:JQuery特效代碼     

以下是一個以 jQuery 撰寫的彈窗(Modal)範例,透過一個半透明的遮罩層搭配置中的內容區塊,點擊按鈕開啟、點擊關閉鈕收合。程式碼淺顯易懂,很適合 jQuery 新手參考(需先具備基本的 jQuery 觀念)。

完整程式碼如下:

<html>
<head>
<title>js 彈窗效果</title>
<meta http-equiv="content-type" content="text/html charset=gb2312">
<script language="javascript" src="jquery-1.4.js"></script>
</head>

<script language="javascript">
function mina(){
    $("#dv").css("display", "block");
    var a = $(document).height();
    var b = $(window).width();
    var h = $(window).height();
    var f = (b - 300) / 2;   // 水平居中
    var d = (h - 300) / 2;   // 垂直居中
    $("#dv").css("margin-top", d);
    $("#dv").css("margin-left", f);
    $("#zhezhao").toggle();
    $("#zhezhao").css("width", b);
    $("#zhezhao").css("height", a);
}
function nin(){
    $("#dv").css("display", "none");
    $("#zhezhao").toggle();
}
</script>
<body>
<div style="display:none;position:absolute;z-index:100;background:#ccc" id="zhezhao"></div>
<input type="button" value="點擊" onclick="mina()">
<div id="dv" style="width:300px;height:300px;border:1px solid red;display:none;position:absolute;z-index:1000;background:white;">
  <div><span id="ss" style="width:30px;height:30px;border:1px solid blue;background:black;float:right;" onclick="nin()"></span></div>
</div>
<table align="center" border="1" width="888" height="668">
  <tr>
    <td align="center">haha</td>
  </tr>
</table>
</body>
</html>

運作說明:點擊「點擊」按鈕觸發 mina(),它會顯示內容區塊 #dv,並依視窗寬高計算出水平與垂直居中的邊距,同時把遮罩層 #zhezhao 的寬高設為整個頁面大小並顯示出來。點擊右上角的關閉區塊則觸發 nin(),隱藏視窗並切換遮罩。透過 z-index 讓遮罩(100)位於內容(1000)之下,就能營造出模態彈窗的視覺效果。

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