傳統彈出視窗使用 window.open 或 showModalDialog,易被瀏覽器攔截、難以包含伺服器控件、樣式受限。ASP.NET 2.0 利用 DIV 層疊定位,配合 JavaScript 控制顯示/隱藏,實現頁內彈出視窗,可包含任意 HTML 與伺服器控件(如 ListBox、GridView),體驗媲美桌面應用程式。
TextBox 掛載 OnClick 呼叫 JS 函式 PopupArea(event, 'divID')。div class="popupWindow" 絕對定位,初始 display:none,內含關閉按鈕與伺服器控件(如 ListBox AutoPostBack="true")。PopupArea 計算座標顯示 DIV;jsAreaClose 隱藏 DIV。<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="ParentPage.aspx.cs" Inherits="PopupWithDiv.ParentPage" %>
<html><head>
<script src="jsPopup.js" type="text/javascript"></script>
<script>
function ProtectBox(e) { return false; } // 禁止輸入
</script>
</head><body>
<form runat="server">
<div id="header"><p>Popup Window with DIV Layer</p></div>
<div id="content">
<table><tr>
<td><label>Country :</label></td>
<td><asp:TextBox ID="txtCountry" runat="server" OnKeyDown="return ProtectBox(event);" OnClick="PopupArea(event, 'divCountry')" /></td>
<td><label>City :</label></td>
<td><asp:TextBox ID="txtCity" runat="server" OnKeyDown="return ProtectBox(event);" OnClick="PopupArea(event, 'divCity')" /></td>
</tr></table>
</div>
<!-- Country Popup -->
<div class="popupWindow" id="divCountry">
<table><tr><td align="right">
<span onclick="jsAreaClose('divCountry')" style="cursor:hand">
<img src="close.gif" border="0" alt="Hide Popup" />
</span></td></tr>
<tr><td><asp:ListBox ID="lstCountry" runat="server" AutoPostBack="True" Width="100%" Rows="10" /></td></tr>
</table>
</div>
<!-- City Popup -->
<div class="popupWindow" id="divCity">
<table><tr><td align="right">
<span onclick="jsAreaClose('divCity')" style="cursor:hand">
<img src="close.gif" border="0" alt="Hide Popup" />
</span></td></tr>
<tr><td><asp:ListBox ID="lsCity" runat="server" AutoPostBack="True" Width="100%" Rows="10" /></td></tr>
</table>
</div>
</form></body></html>
function PopupArea(e, divId) {
var div = document.getElementById(divId);
div.style.left = e.clientX + document.body.scrollLeft + 'px';
div.style.top = e.clientY + document.body.scrollTop + 'px';
div.style.display = 'block';
}
function jsAreaClose(divId) {
document.getElementById(divId).style.display = 'none';
}
DIV 層彈出視窗是 ASP.NET 2.0 時代打造豐富 Web UI 的經典模式,奠定了後來 jQuery UI Dialog、Bootstrap Modal 等元件的基礎概念。