您的位置:首页 > Web前端 > JavaScript

ASP.NET&Javascript实现半透明背景&模式弹出个性化页面实例

2010-01-06 14:35 821 查看
开发Web应用时,经常会有弹出模式对话框的情况,可以直接调用window.showModalDialog()方法,一般情况就可以了。

但有一些应用场景,需要我们弹出一些自定义控件或页面,同时用一层半透明的背景将页面的其他地方遮住,以防止用户的其他操作,以达到一种“模式窗口”的效果,这里给出一个实现此类效果,同时支持弹出自定义控件页面中通过委托更新主页面的操作功能,当然,此应用支持IE和FireFox两种浏览器。

  


详细代码脚本及页面代码如下:

a) CSS样式:Base.css文件

div.Container { width:700px; min-height:300px; border:solid 1px #003366; background-image:url(/images/PopupBG.gif); background-repeat:repeat-x; background-color:#d9e1e8; }
div.Content { width:640px; min-height:280px; margin-left:30px; margin-top:20px; }
div.ShieldBG { background-color:Gray; filter:alpha(opacity=50); -moz-opacity:0.5; opacity:0.5;}
div.ItemRow { display:inline; }

b) Javascript脚本:PositionCaculate.js文件

1 //
2 // Object for parameters.
3 var MemberParameters = {
4 // Id of container div.
5 ContainerDivId: "div_Container",
6 // Id of ShieldBG.
7 ShieldBGId : "div_ShieldBG",
8 // Class Name of ShieldBG.
9 ShieldBGClassName: "ShieldBG",
10 // Number of z-index of ShieldBG.
11 ShieldBGZIndex: 100,
12 // Whether scroll tag.
13 IsScroll: false,
14 // Default space for pop-up layout to left and top.
15 DefaultSpace: 50
16 };
17
18 //
19 // Object for logical modules.
20 var LogicalModules = {
21 //
22 // Show up the content layout.
23 PopUpContainerDiv: function() {
24 // Init.
25 var objContainerDiv = document.getElementById(MemberParameters.ContainerDivId);
26 // Check.
27 if (objContainerDiv == null || objContainerDiv.parentNode == null)
28 return false;
29 // Set the style of container.
30 objContainerDiv.style.position = "absolute";
31 objContainerDiv.style.zIndex = MemberParameters.ShieldBGZIndex + 1;
32 // Show the content layout.
33 objContainerDiv.style.display = "";
34 // Show up orCreate a new bg div and set the style.
35 var objShieldBg = document.getElementById(MemberParameters.ShieldBGId);
36 if (objShieldBg != null) {
37 objShieldBg.style.display = "";
38 } else {
39 var objNewDiv = document.createElement("DIV");
40 objNewDiv.setAttribute("id", MemberParameters.ShieldBGId);
41 objNewDiv.style.position = "absolute";
42 objNewDiv.style.zIndex = MemberParameters.ShieldBGZIndex;
43 objNewDiv.style.top = "0px";
44 objNewDiv.style.left = "0px";
45 // Set the class name.
46 objNewDiv.className = MemberParameters.ShieldBGClassName;
47 // Append it.
48 objContainerDiv.parentNode.appendChild(objNewDiv);
49 }
50 //
51 // Caculate the width and height.
52 this.CaculateWidthAndHeight();
53 //// If you want to keep the layout on the changeless position, use this.
54 // Add the reflesh events.
55 // this.AddScrollEvent();
56 ////
57 },
58 //
59 // Hide the content layout.
60 HideContainerDiv: function() {
61 var objContainerDiv = document.getElementById(MemberParameters.ContainerDivId);
62 var objShieldBg = document.getElementById(MemberParameters.ShieldBGId);
63 if (objContainerDiv == null || objShieldBg == null)
64 return false;
65 objContainerDiv.style.display = "none";
66 objShieldBg.style.display = "none";
67 //// If you want to keep the layout on the changeless position, use this.
68 // Remove the reflesh events.
69 // this.RemoveScrollEvent();
70 ////
71 },
72 //
73 // Caculate the widht and height.
74 CaculateWidthAndHeight: function() {
75 // Defind.
76 var clientWidth = document.documentElement.clientWidth;
77 var clientHeight = document.documentElement.clientHeight;
78 // Get the objs.
79 var objContainer = document.getElementById(MemberParameters.ContainerDivId);
80 var objShieldBg = document.getElementById(MemberParameters.ShieldBGId);
81 if (objContainer == null || objShieldBg == null)
82 return false;
83 // Bg width and height.
84 var bgWidth = Math.max(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), clientWidth);
85 var bgHeight = Math.max(document.body.scrollHeight, clientHeight);
86 // Container width and height.
87 var containerWidth = (clientWidth - objContainer.clientWidth) / 2;
88 var containerHeight = (clientHeight - objContainer.clientHeight) / 2;
89 // Adjust the values.
90 if (containerWidth < 0)
91 containerWidth = MemberParameters.DefaultSpace;
92 if (containerHeight < 0)
93 containerHeight = MemberParameters.DefaultSpace;
94 // Check the container's width and height.
95 if (objContainer.clientHeight > bgHeight)
96 bgHeight = containerHeight + objContainer.clientHeight + MemberParameters.DefaultSpace;
97 if (objContainer.clientWidth > bgWidth)
98 bgWidth = containerWidth + objContainer.clientWidth + MemberParameters.DefaultSpace;
99 // Update the IsScroll status.
if (bgHeight > clientHeight || bgWidth > clientWidth) {
MemberParameters.IsScroll = true;
bgHeight += MemberParameters.DefaultSpace;
}
// Set values.
objContainer.style.left = containerWidth + "px";
objContainer.style.top = containerHeight + "px";
objShieldBg.style.width = bgWidth + "px";
objShieldBg.style.height = bgHeight + "px";
},
//
// Set the event to reflesh the pop-up layout.
AddScrollEvent: function() {
if (MemberParameters.IsScroll) {
AssistantFunctions.AddEvent(window, "onscroll", this, this.CaculateWidthAndHeight);
AssistantFunctions.AddEvent(window, "onresize", this, this.CaculateWidthAndHeight);
}
},
//
// Remove the events to reflesh the pop-up layout.
RemoveScrollEvent: function() {
if (MemberParameters.IsScroll) {
AssistantFunctions.RemoveEvent(window, "onscroll", this, this.CaculateWidthAndHeight);
AssistantFunctions.RemoveEvent(window, "onresize", this, this.CaculateWidthAndHeight);
}
}
};

//
// Objects for assistant functions.
var AssistantFunctions = {
//
// Add Event to window.
AddEvent: function(obj, event, source, func) {
if (obj.attachEvent) {
// IE.
obj.attachEvent(event, function() { func.apply(source, arguments); });
}
else {
// FF.
obj.addEventListener(event, func, false);
}
},
//
// Remove Event from window.
RemoveEvent: function(obj, event, source, func) {
if (obj.detachEvent) {
// IE.
obj.detachEvent(event, func);
}
else {
// FF.
obj.removeEventListener(event, func, false);
}
}
};

//
// Objects for app invoke.
var AppInvokes = {
//
// Pop up the layout contain some content.
PopUpContainerDiv: function() {
LogicalModules.PopUpContainerDiv();
},
//
// Hide the layout.
HideContainerDiv: function() {
LogicalModules.HideContainerDiv();
}
};

//
// Object for tests.
var AppTests = {

};

c) 主页面:Default.aspx文件及后台

i. 前台:

1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebAppForCustomControlTest._Default" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <%@ Register Src="~/WebUserControlFir.ascx" TagName="NewControl" TagPrefix="uu1" %>
6
7 <html xmlns="http://www.w3.org/1999/xhtml" >
8 <head runat="server">
9 <title>Web Custom Control Test</title>
<link type="text/css" href="Css/Base.css" rel="Stylesheet" />
<script src="Javascript/PositionCalculate.js" type="text/javascript"></script>
<script type="text/javascript">

function UpdateReturnStr(sReturn) {
var objText = document.getElementById("txtReturnStr");
if (objText != null) {
objText.value = sReturn;
}
}

</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="SM" runat="server"></asp:ScriptManager>
<div>
<label>Client Return Value: </label>
<input type="text" id="txtReturnStr" value="No Return, Client!" />
<asp:UpdatePanel ID="upd_Result" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Text="Server Return Value:" runat="server"></asp:Label>
<asp:TextBox ID="txtReturnStrSvr" Text="No Return, Server!" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<input type="button" value="Click Me to Pop-up New Layout" onclick="AppInvokes.PopUpContainerDiv()" />
</div>
<div id="div_Container" style=" display:none;" class="Container">
<div class="Content">
<asp:UpdatePanel ID="upd_PopUpControl" runat="server">
<ContentTemplate>
<uu1:NewControl ID="wuc_PopUpControl" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</form>
</body>
</html>

ii. 后台:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7
8 namespace WebAppForCustomControlTest
9 {
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// init the web user control.
wuc_PopUpControl.PopUpScript = "AppInvokes.PopUpContainerDiv()";
wuc_PopUpControl.HideScript = "AppInvokes.HideContainerDiv()";
wuc_PopUpControl.ReturnContent += new WebUserControlFir.ReturnEventHandler(wuc_PopUpControl_ReturnContent);
}

private void wuc_PopUpControl_ReturnContent(object source, ReturnClass rc)
{
if (rc != null && !string.IsNullOrEmpty(rc.Name) && !string.IsNullOrEmpty(rc.Value))
{
txtReturnStrSvr.Text = string.Format("{0}:{1}", rc.Name, rc.Value);
upd_Result.Update();
}
}
}
}

d) 自定义控件:WebUserControlFir.ascx文件及后台

i. 前台:

1 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControlFir.ascx.cs" Inherits="WebAppForCustomControlTest.WebUserControlFir" %>
2 <script type="text/javascript">
3 function GetInputValue() {
4 var objInput = document.getElementById("<%=txtInput.ClientID%>");
5 if (objInput != null)
6 UpdateReturnStr(objInput.value);
7 }
8 </script>
9
<div>
<label>This is a test web custom control, so if you see this page, you have pop up this control.</label>
<br />
<br />
<asp:TextBox ID="txtInput" runat="server" Text="" Width="150px" TextMode="SingleLine"></asp:TextBox>
<br />
<asp:Button ID="btnClose" runat="server" Text="Return String Server" OnClick="OnClick_btnClose" />
<br />
<asp:Button ID="btnChangeContent" runat="server" Text="ChangeListContent" OnClick="OnClick_btnChangeContent" />
<br />
<input type="button" id="btnCloseClient" value="Return String Client" onclick="GetInputValue()" />
<asp:Label ID="labProcResult" Text="" runat="server"></asp:Label>
<br />
<asp:ListView ID="livData" runat="server">
<ItemTemplate>
<div>
<div class="ItemRow">
<asp:Label ID="labName" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
</div>
<div class="ItemRow">
<asp:Label ID="labAddress" runat="server" Text='<%#Eval("Address") %>'></asp:Label>
</div>
<div class="ItemRow">
<asp:Label ID="labPhone" runat="server" Text='<%#Eval("Phone") %>'></asp:Label>
</div>
</div>
</ItemTemplate>
<LayoutTemplate>
<div>
<div>
<div class="ItemRow">Name</div>
<div class="ItemRow">Address</div>
<div class="ItemRow">Phone</div>
</div>
<div>
<div id="itemPlaceholder" runat="server"></div>
</div>
</div>
</LayoutTemplate>
</asp:ListView>
</div>

ii. 后台:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7
8 namespace WebAppForCustomControlTest
9 {
public partial class WebUserControlFir : System.Web.UI.UserControl
{
public delegate void ReturnEventHandler(object source, ReturnClass rc);
public event ReturnEventHandler ReturnContent;

public string HideScript { set; get; }
public string PopUpScript { set; get; }

protected void Page_Load(object sender, EventArgs e)
{
List<PersonClass> Persons = new List<PersonClass>();
for (int i = 0; i < 8; i++)
{
PersonClass p = new PersonClass() { Name = "User", Address = "Beijing", Phone = "01000000000" };
Persons.Add(p);
}

livData.DataSource = Persons;
livData.DataBind();
}

protected void OnClick_btnClose(object sender, EventArgs e)
{
labProcResult.Text = "Great, you've send the string you input to the main page!";
string InputStr = txtInput.Text;
if (!string.IsNullOrEmpty(InputStr))
{
ReturnClass rc = new ReturnClass();
rc.Name = txtInput.ID;
rc.Value = InputStr;
ReturnContent(this, rc);
ScriptManager.RegisterStartupScript(labProcResult, labProcResult.GetType(), "ReturnAndClose", HideScript, true);
}
}

protected void OnClick_btnChangeContent(object sender, EventArgs e)
{
List<PersonClass> Persons = new List<PersonClass>();
for (int i = 0; i < 70; i++)
{
PersonClass p = new PersonClass() { Name="User", Address="Beijing", Phone="01000000000"};
Persons.Add(p);
}

livData.DataSource = Persons;
livData.DataBind();

ScriptManager.RegisterStartupScript(labProcResult, labProcResult.GetType(), "Reload", PopUpScript, true);
}
}

public class PersonClass
{
public string Name { set; get; }
public string Address { set; get; }
public string Phone { set; get; }
}
}

工程源代码下载链接如下:

/Files/guilin_gavin/WebAppForCustomControlTest.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: