我想使用TextBox
和Calendar
来创建日期选择字段,如下所示,
<asp:TextBox ID="date_selected" Enabled="false" CssClass="date" runat="server" MaxLength="10"></asp:TextBox>
<asp:ImageButton ID="image_calendar" runat="server" Width="32px" ImageAlign="AbsMiddle" Height="32px" ImageUrl="/Images/calendar.png" OnClick="image_calendar_Click"></asp:ImageButton>
<asp:Calendar ID="calendar" Visible="false" runat="server" OnSelectionChanged="calendar_SelectionChanged"></asp:Calendar>
在此点击ImageButton
,Calendar
将变为可见,点击日期后,TextBox
将使用下面的脚本填充该日期,
protected void image_calendar_Click(object sender, ImageClickEventArgs e)
{
calendar.Visible = true;
}
protected void calendar_SelectionChanged(object sender, EventArgs e)
{
date_selected.Text = calendar.SelectedDate.ToShortDateString().ToString();
calendar.Visible = false;
}
但我想在不使用ImageButton
的情况下执行此操作,当我点击TextBox
本身时,应显示Calendar
。但是TextBox
没有任何OnClick
功能。是否有其他方法可以使用TextBox:focus
中的CSS
或使用JavaScript
或JQuery
来执行此操作?
在CSS
我知道我们可以使用属性display: none
和&#39; visibility:hidden`隐藏项目的可见性,但有没有办法在下面执行此操作?
#date_selected:focus {
// set visibility of Calendar to "visible"
}
最终代码(编辑)
以下是我正在使用的最终代码。
ASP.NET
<asp:TextBox ID="date_selected" ReadOnly="true" MaxLength="10" AutoPostBack="true" runat="server"></asp:TextBox>
<asp:Calendar ID="calendar" runat="server" OnSelectionChanged="calendar_SelectionChanged"></asp:Calendar>
C#
protected void calendar_SelectionChanged(object sender, EventArgs e)
{
date_selected.Text = calendar.SelectedDate.ToShortDateString().ToString();
calendar.Visible = false;
}
CSS
#calendar {
visibility: hidden;
opacity: 0;
position: absolute;
z-index : 9999 !important;
}
#date_selected:focus ~ #calendar {
visibility: visible;
position: absolute;
opacity: 1;
}
但是在显示日历后,即使我点击任何日期,它也没有在文本框中更新?我不确定为什么?不只是在任何日期,如果我点击日历上的任何地方,日历就会消失,我甚至无法更改月份。也许当我点击日历上的某个地方时,文本框上的焦点消失了,日历也消失了。我该如何解决这个问题?
答案 0 :(得分:1)
将其置于其他div之上,您可以使用z-index
#date_selected:focus ~ #calendar {
visibility: visible;
position: absolute;
opacity: 1;
z-index : 9999 !important;
}
此外,使用Jquery
,您应该将其放在document ready
函数中以使其正常工作
$(document).ready(function () {
$('#date_selected').focus(function() { $('#Calendar ').show(); });
});
如果您想添加日历功能,还可以使用datepicker。它是Jquery中一个漂亮,简单且易于使用的插件。使用datepicker
您不必再设置css和日历了。然后你会像这样使用它:
$(document).ready(function () {
$('#date_selected').datepicker();
});
答案 1 :(得分:0)
您只需使用Ajax Toolkit
即可完成上述操作,请尝试下面的
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" PopupButtonID="txtDate" >
</cc1:CalendarExtender>
</div>
</form>