效果:当光标落入TextBox中,其下出现日历.日历是asp.net 的日历控件.
(1)aspx中代码:
JavaScript部分:
<script language="javascript" type="text/javascript">
function getAbsolutePosition(element)
{
var point = { x: element.offsetLeft, y: element.offsetTop };
if (element.offsetParent)
{
var parentPoint = this.getAbsolutePosition(element.offsetParent);
point.x += parentPoint.x;
point.y += parentPoint.y;
}
return point;
};
function myclick()
{
var myTextbox=document.getElementById("myRegisterTime");
var point1 = getAbsolutePosition(myTextbox);
document.getElementById("caDiv").style.display="block";
document.getElementById("caDiv").style.left=point1.x;
document.getElementById("caDiv").style.top=point1.y;
}
function divonclick()
{
document.getElementById("caDiv").style.display="none";
}
</script>
页面控件:
<asp:TextBox ID="myRegisterTime" runat="server" width="220px"></asp:TextBox>
<div id="caDiv" style="display:none;position: absolute;" οnclick="divonclick()">
<asp:Calendar ID="Calendar1" runat="server" BackColor="White"
BorderColor="#3366CC" Font-Names="Verdana" Font-Size="8pt"
ForeColor="#003399" Height="200px" Width="220px"
onselectionchanged="Calendar1_SelectionChanged" BorderWidth="1px"
CellPadding="1" DayNameFormat="Shortest">
<SelectedDayStyle BackColor="#009999" ForeColor="#CCFF99" Font-Bold="True" />
<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
<WeekendDayStyle BackColor="#CCCCFF" />
<TodayDayStyle BackColor="#CCCCCC" />
<OtherMonthDayStyle ForeColor="#999999" />
<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
<TitleStyle BackColor="#003399" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF"
BorderColor="#3366CC" BorderWidth="1px" Height="25px" />
</asp:Calendar>
</div>
后台代码:
//页面加载
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myRegisterTime.Attributes.Add("onfocus", "javascript:myclick()");
}
}
//日历事件
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
if (Calendar1.SelectedDate > DateTime.Now.AddDays(-1.0))
myRegisterTime.Text = Calendar1.SelectedDate.ToLongDateString();
else
{
WebHelper.Alert("日期无效,请重选!");
Calendar1.SelectedDate = DateTime.Now;
}
}
心得:一个小小的功能花费了我将近一天的时间,主要受困于,div样式设置,特别是position的属性设置不对时,效果出不来,div定位不正确.还有就是,日历的隐藏与显示时,采用的是对其外部的div控制来实现的,因为日历是服务器控件,当他的visible为false时,生成的页面将不会出现相应日历html代码,JavaScript将无法调用,程序将会提示,引用错误.....因而在与JavaScript结合使用时visble属性一般不用于控制显示或隐藏,而是用style下的display属性.....
.......如果有什么不当,望指正...