【问题标题】:html5 time type and placeholderhtml5时间类型和占位符
【发布时间】:2018-12-26 03:28:57
【问题描述】:

有没有办法在 type="time" 的文本框中设置占位符? 现在它显示时间输入格式,如 --:-- 但我想显示为“开始时间”和“结束时间”(在文本框内,而不是在外部标签上)

<asp:TextBox ID="StartingHour" Type="time" runat="server" placeholder="Start Time" required="required" />

这表明 --:--

谢谢

【问题讨论】:

  • 当您想设置占位符时 - 失去焦点时或任何时候?目前time 输入控件占位符取决于浏览器实现。

标签: asp.net html textbox placeholder


【解决方案1】:

placeholder 属性设置取决于客户端浏览器对&lt;input type="time" /&gt; 的行为方式,但如果您想在用户未选择输入控件时显示占位符,您可以尝试以下解决方法:

ASPX

<asp:TextBox ID="StartingHour" runat="server" placeholder="Start Time" required="required" />

JS (jQuery)

// when getting focus
$('#<%= StartingHour.ClientID %>').focus(function () {
    $(this).attr('type', 'time'); 
});

// when losing focus
$('#<%= StartingHour.ClientID %>').focusout(function () {
    $(this).attr('type', 'text'); 
});

注意:同样的方法可以用来控制EndingHour的占位符。

JSFiddle Example

更新 1:

如果您想使用公共前缀(如txtHour)输入控件,您可以将ClientID模式设置为Static并使用前缀作为选择器:

<asp:TextBox ID="txtHour1" runat="server" ClientIDMode="Static" placeholder="Time" required="required" />

<asp:TextBox ID="txtHour2" runat="server" ClientIDMode="Static" placeholder="Time" required="required" />

JS (jQuery)

// when getting focus
$('input[id^="txtHour"]').focus(function () {
    $(this).attr('type', 'time'); 
});

// when losing focus
$('input[id^="txtHour"]').focusout(function () {
    $(this).attr('type', 'text'); 
});

或使用分配给所有相关文本框控件的共享 CSS 类:

<asp:TextBox ID="txtHour1" runat="server" CssClass="hour" placeholder="Time" required="required" />

<asp:TextBox ID="txtHour2" runat="server" CssClass="hour" placeholder="Time" required="required" />

JS (jQuery)

// when getting focus
$('.hour').focus(function () {
    $(this).attr('type', 'time'); 
});

// when losing focus
$('.hour').focusout(function () {
    $(this).attr('type', 'text'); 
});

类似问题:Can I use placeholder in <input type="time"/>

【讨论】:

  • 不错的解决方法!但是如何更改 jscript 以将其应用于以特定字符串开头的每个控件 ID?假设我所有的时间文本框都有前缀“txtHour”,我可以使用相同的 jscript 而不必指定每个文本框的实际 ID 吗?
  • 如果您有txtHour1txtHour2 等控件ID,则可以将该前缀用作$('input[id^="txtHour"]') 等jQuery 选择器。但是,这只有在 ClientID 模式设置为 static 时才有效,因此我建议您使用通用 CSS 类并将其用作选择器。
猜你喜欢
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2011-06-18
  • 2020-06-20
  • 2023-04-08
  • 2011-06-22
相关资源
最近更新 更多