该文章转自Clark的文章,原文出处:http://blog.csdn.net/reonlyrun/archive/2006/12/27/1464372.aspx
在网上查阅了很多相关资料,参照对比一番后自己整理了一下,做了个小例子。能够实现根据后台数据加载的进度在前台动态更新进度条、进度条在页面居中显示、在进度条内显示百分比,完成进度后隐藏进度条。个人感觉还是有一定的参考价值,贴出来先。
建立一个WEB工程,添加新项->HTML页面,命名为ProgressBar.htm,内容如下:
1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">2
<html xmlns="http://www.w3.org/1999/xhtml" id="mainWindow">3
<head>4
<title>无标题页</title>5
<script language="javascript">6
function SetPorgressBar(pos)7

{8
//设置进度条居中9
var screenHeight = window["mainWindow"].offsetHeight;10
var screenWidth = window["mainWindow"].offsetWidth;11
ProgressBarSide.style.width = Math.round(screenWidth / 2);12
ProgressBarSide.style.left = Math.round(screenWidth / 4);13
ProgressBarSide.style.top = Math.round(screenHeight / 2);14
ProgressBarSide.style.height = "21px";15
ProgressBarSide.style.display = "";16
17
//设置进度条百分比 18
ProgressBar.style.width = pos + "%";19
ProgressText.innerHTML = pos + "%";20
}21

22
//完成后隐藏进度条23
function SetCompleted()24

{ 25
ProgressBarSide.style.display = "none";26
}27
</script> 28
</head>29
<body>30
<div id="ProgressBarSide" style="position:absolute;height:21x;width:100px;color:Silver;border-width:1px;border-style:Solid;display:none">31
<div id="ProgressBar" style="position:absolute;height:21px;width:0%;background-color:#3366FF"></div>32
<div id="ProgressText" style="position:absolute;height:21px;width:100%;text-align:center"></div>33
</div>34
</body>35
</html>后台代码,Default.aspx.cs:
1
using System;2
using System.Data;3
using System.Configuration;4
using System.Web;5
using System.Web.Security;6
using System.Web.UI;7
using System.Web.UI.WebControls;8
using System.Web.UI.WebControls.WebParts;9
using System.Web.UI.HtmlControls;10
using System.Threading;11
using System.IO;12

13
public partial class _Default : System.Web.UI.Page 14


{15
private void beginProgress()16

{17
//根据ProgressBar.htm显示进度条界面18
string templateFileName = Path.Combine(Server.MapPath("."), "ProgressBar.htm");19
StreamReader reader = new StreamReader(@templateFileName,System.Text.Encoding.GetEncoding("GB2312"));20
string html = reader.ReadToEnd();21
reader.Close();22
Response.Write(html);23
Response.Flush();24
}25

26
private void setProgress(int percent)27

{28
string jsBlock = "<script>SetPorgressBar('" + percent.ToString() + "'); </script>";29
Response.Write(jsBlock);30
Response.Flush();31
}32

33
private void finishProgress()34

{35
string jsBlock = "<script>SetCompleted();</script>";36
Response.Write(jsBlock);37
Response.Flush();38
}39

40
private void Page_Load(object sender, System.EventArgs e) 41

{42
beginProgress();43

44
for (int i = 1; i <= 100; i++)45

{46
setProgress(i);47

48
//此处用线程休眠代替实际的操作,如加载数据等49
System.Threading.Thread.Sleep(50);50
}51

52
finishProgress(); 53
} 54
}
前台页面代码在此省略,可以放置任意控件。