使用jquery输入时间掩码
问题描述:
我正在使用meioMask - 一个jQuery掩码插件将时间掩码放入文本框中。这里是JsFiddle。它运作良好。但我还需要在文本框中输入hh:mm
,以便让用户知道要在文本框中输入的内容。使用jquery输入时间掩码
如何做到这一点。
编辑:我也需要把am/pm放在面具上。我需要12小时的时间格式。
答
它看起来像你应该能够与插件设置。
这是一个可能的开始?
如果你看看代码,我认为你应该通过setMask
和options
对象。它看起来像defaultValue
是一个可能的选择。
它看起来像下面应该工作(但事实并非如此):
$("#txtTime").setMask({mask: "time", defaultValue:"hh:mm"});
这就是我一直在寻找:
$.fn.extend({
setMask : function(options){
return $.mask.set(this, options);
},
而且
// default settings for the plugin
options : {
attr: 'alt', // an attr to look for the mask name or the mask itself
mask: null, // the mask to be used on the input
type: 'fixed', // the mask of this mask
maxLength: -1, // the maxLength of the mask
defaultValue: '', // the default value for this input
答
我想这可能工作
$(document).ready(function(){
$("#txtTime").setMask('time').val('hh:mm');
})
答
可以使用HTML5 placeholder
属性创建占位符文本,然后使用jQuery来添加对不支持它的浏览器的支持,并删除它一旦获得焦点,就会成为input
元素。
var timeTxt = $("#txtTime").setMask('time');
var placeholder = timeTxt.attr('placeholder');
timeTxt.val(placeholder).focus(function(){
if(this.value === placeholder){
this.value = '';
}
}).blur(function(){
if(!this.value){
this.value = placeholder;
}
});
参见:http://www.jsfiddle.net/9dgYN/2/。您还应该考虑使用诸如Modernizr之类的脚本来为placeholder
属性添加功能检测。
答
如果你希望它简单和干净,这里是一个快速但完整的演示(请参阅:http://jsfiddle.net/bEJB2/),其中包括一个placeholder
和一个面具一起工作。它使用jQuery Plugin jquery.maskedinput。 JavaScript的是那么干净,清晰
<div class="time-container">
<h1> Demo of Mask for 12 Hour AM/PM Input Field w/ Place Holder </h1>
<input class="timepicker" type="text" size="10" placeholder="hh:mm PM" />
</div>
<script>
$.mask.definitions['H'] = "[0-1]";
$.mask.definitions['h'] = "[0-9]";
$.mask.definitions['M'] = "[0-5]";
$.mask.definitions['m'] = "[0-9]";
$.mask.definitions['P'] = "[AaPp]";
$.mask.definitions['p'] = "[Mm]";
$(".timepicker").mask("Hh:Mm Pp");
</script>
我想重复一下@YiJiang说,大约为PolyFills and Modernizr在placeholder
非HTML5浏览器处理为好。
答
使用jQuery Masked Input Plugin。
$.mask.definitions['H'] = "[0-2]";
$.mask.definitions['h'] = "[0-9]";
$.mask.definitions['M'] = "[0-5]";
$.mask.definitions['m'] = "[0-9]";
$(".timepicker").mask("Hh:Mm", {
completed: function() {
var currentMask = $(this).mask();
if (isNaN(parseInt(currentMask))) {
$(this).val("");
} else if (parseInt(currentMask) > 2359) {
$(this).val("23:59");
};
}
});
为什么我不能使用setMask()? 'Uncaught TypeError:Object [object Object] has no method'setMask''其他jquery代码正常工作。另外,我没有在jquery.com上看到任何对setMask的引用。 – marquito 2012-09-13 17:00:18