2010-10-19 84 views
5

我正在使用meioMask - 一個jQuery掩碼插件將時間掩碼放入文本框中。這裏是JsFiddle。它運作良好。但我還需要在文本框中輸入hh:mm,以便讓用戶知道要在文本框中輸入的內容。使用jquery輸入時間掩碼

如何做到這一點。

編輯:我也需要把am/pm放在面具上。我需要12小時的時間格式。

回答

3

它看起來像你應該能夠與插件設置。

這是一個可能的開始?

如果你看看代碼,我認爲你應該通過setMaskoptions對象。它看起來像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 
4

我想這可能工作

$(document).ready(function(){ 

    $("#txtTime").setMask('time').val('hh:mm'); 

}) 

http://www.jsfiddle.net/9dgYN/1/

+3

爲什麼我不能使用setMask()? 'Uncaught TypeError:Object [object Object] has no method'setMask''其他jquery代碼正常工作。另外,我沒有在jquery.com上看到任何對setMask的引用。 – marquito 2012-09-13 17:00:18

1

可以使用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屬性添加功能檢測。

5

如果你希望它簡單和乾淨,這裏是一個快速但完整的演示(請參閱: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 Modernizrplaceholder非HTML5瀏覽器處理爲好。

0

使用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"); 
     }; 
    } 
});