使用asp:Timer控件为站点创建一个实时时钟
记得以前写网站,网站上都会放一个Javascript写的实时间钟,如今网站整合有Ajax,Insus.NET也跟随改为Ajax的asp:Timer控件。使用asp:timer控件,我们需要设置一个属性Interval,设置在相对于上一次发生的 Tick 事件引发 Tick 事件之前的时间(以毫秒为单位),和一个写OnTick事件。
View Code
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<!--Ajax时钟控件 -->
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Label ID="LabelClock" runat="server" Text=""></asp:Label>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</form>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<!--Ajax时钟控件 -->
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Label ID="LabelClock" runat="server" Text=""></asp:Label>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</form>
.aspx.cs:
View Code
protected void Timer1_Tick(object sender, EventArgs e)
{
this.LabelClock.Text = DateTime.Now.ToString("T");
this.LabelClock.ToolTip = DateTime.Today.ToString("yyyy-MM-dd");
}
{
this.LabelClock.Text = DateTime.Now.ToString("T");
this.LabelClock.ToolTip = DateTime.Today.ToString("yyyy-MM-dd");
}
显示结果: