最近需要用到一个时分秒的插件,搜索了一下,没有找到合适的。就自己动手写了一个。
实现的原理就是点击输入框的时候,会弹出动态生成的选择时分秒的div,点击确定按钮会读取选择的时分秒写入输入框中,然后动态移除div。代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>时分秒</title> <script src="http://apps.bdimg.com/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> .time-label{ position: relative; } .contents{ position: absolute; left: 0; top: 30px; z-index: 10; background-color: red; } .time-ipt{ width: 200px; height: 20px; border-radius: 3px; } </style> </head> <body> <label class="time-label"> <input class='time-ipt' type="text" readonly data-len=3 /> </label> </body> <script type="text/javascript"> $('.time-label').on('click','.time-ipt',function(len){ //参数lenth为时间长度,如果时分秒则len==3,如果时分则len==2 var len = $(this).attr('data-len') var height = $(this).height() + 10; var width = $(this).width() + 30; //动态生成选择器 var _str = '' _str += "<div class='contents'><select class='hour' name='hour'>"; for (h = 0; h <= 9; h++) { _str += '<option value=0' + h + '>0' + h + '</option>'; } for (h = 10; h <= 23; h++) { _str += '<option value=' + h + '>' + h + '</option>'; } _str += "</select>时<select class='minute' name='minute'>"; for (m = 0; m <= 9; m++) { _str += '<option value=0'+ m + '>0' + m + '</option>'; } for (m = 10; m <= 59; m++) { _str += '<option value='+ m + '>' + m + '</option>'; } // if(len == 3){ _str += "</select>分<select class='second' name='second'>"; for (s = 0; s <= 9; s++) { _str += '<option value=0'+ s + '>0' + s + '</option>'; } for (s = 10; s <= 59; s++) { _str += '<option value='+ s + '>' + s + '</option>'; } _str += "</select>秒 <button class='time-btn'>确定</button></div>"; }else if(len == 2){ _str += "</select>秒<button class='time-btn'>确定</button></div>"; } $(_str).insertAfter($(this)); $(this).siblings('.contents').css('top',height + 'px').css('width',width + 'px'); $(this).attr('disabled',true); }) $(document).ready(function(){ //点击确定按钮给时间框赋值,然后删除动态生成的div $('.time-label').on('click','.time-btn',function(event,len){ var len = $(this).parent().siblings('.time-ipt').attr('data-len'); if(len == 3){ var h = $(this).siblings('.hour').val(); var m = $(this).siblings('.minute').val(); var s = $(this).siblings('.second').val(); var nowtime = h + ':' + m + ':' + s $(this).parent().siblings('.time-ipt').val(nowtime); }else if(len == 2){ var h = $(this).siblings('.hour').val(); var m = $(this).siblings('.minute').val(); var nowtime = h + ':' + m $(this).parent().siblings('.time-ipt').val(nowtime); } $(this).attr('disabled',true); $(this).parent().siblings('.time-ipt').attr('disabled',false); $(this).parent().remove(); return false; }) }); </script> </html>
经测试,兼容各大主流浏览器。