蒋志新.com

专注WEB开发

js日历控件介绍及使用详解

一个项目中,很多时候我们都需要选择时间的功能,一种能够将时间格式统一化的方法对于数据存储来说额为重要,然而使用一般文本框的形式或者下拉框的形式来完成这个功能的话就会比较繁琐,那么如何来用一个简单方法来实现这个功能呢,最理想的方式当然是使用日历控件了!
使用以下方法将会让你的程序减少不少麻烦,而且很美观哦!^ _ ^

首先,想使用日历,当然需要一个js日历控件了,新建一个Calendar.js文件(有了这个文件,以后想使用时调用以下就可以了,超方便),加入以下代码:

  1. <!--
  2. var cal;
  3. var isFocus=false; //是否为焦点
  4. //function SelectDate(obj,strFormat) //两个参数改为只传一个
  5. function SelectDate(obj)
  6. {
  7.     var date = new Date();
  8.     var by = date.getFullYear()-10; //最小值 → 10 年前
  9.     var ey = date.getFullYear()+10; //最大值 → 10 年后
  10.     cal = (cal==null) ? new Calendar(by, ey, 0) : cal;    //初始化为中文版,1为英文版
  11.     //cal.dateFormatStyle = strFormat; // 默认显示格式为:yyyy-MM-dd ,还可显示 yyyy/MM/dd
  12.     cal.show(obj);
  13. }
  14. /**//* 返回日期 */
  15. String.prototype.toDate = function(style){
  16. var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年
  17. var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月
  18. var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日
  19. if(isNaN(y)) y = new Date().getFullYear();
  20. if(isNaN(m)) m = new Date().getMonth();
  21. if(isNaN(d)) d = new Date().getDate();
  22. var dt ;
  23. eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')");
  24. return dt;
  25. }
  26. /**//* 格式化日期 */
  27. Date.prototype.format = function(style){
  28. var o = {
  29.     "M+" : this.getMonth() + 1, //month
  30.     "d+" : this.getDate(),      //day
  31.     "h+" : this.getHours(),     //hour
  32.     "m+" : this.getMinutes(),   //minute
  33.     "s+" : this.getSeconds(),   //second
  34.     "w+" : "天一二三四五六".charAt(this.getDay()),   //week
  35.     "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
  36.     "S" : this.getMilliseconds() //millisecond
  37. }
  38. if(/(y+)/.test(style)){
  39.     style = style.replace(RegExp.$1,
  40.     (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  41. }
  42. for(var k in o){
  43.     if(new RegExp("("+ k +")").test(style)){
  44.       style = style.replace(RegExp.$1,
  45.         RegExp.$1.length == 1 ? o[k] :
  46.         ("00" + o[k]).substr(("" + o[k]).length));
  47.     }
  48. }
  49. return style;
  50. };
  51.  
  52. /**//*
  53. * 日历类
  54. * @param   beginYear 1990
  55. * @param   endYear   2010
  56. * @param   lang      0(中文)|1(英语) 可自由扩充
  57. * @param   dateFormatStyle "yyyy-MM-dd";
  58. */
  59. function Calendar(beginYear, endYear, lang, dateFormatStyle){
  60. this.beginYear = 1990;
  61. this.endYear = 2010;
  62. this.lang = 0;            //0(中文) | 1(英文)
  63. this.dateFormatStyle = "yyyy-MM-dd";
  64.  
  65. if (beginYear != null && endYear != null){
  66.     this.beginYear = beginYear;
  67.     this.endYear = endYear;
  68. }
  69. if (lang != null){
  70.     this.lang = lang
  71. }
  72.  
  73. if (dateFormatStyle != null){
  74.     this.dateFormatStyle = dateFormatStyle
  75. }
  76.  
  77. this.dateControl = null;
  78. this.panel = this.getElementById("calendarPanel");
  79. this.container = this.getElementById("ContainerPanel");
  80. this.form = null;
  81.  
  82. this.date = new Date();
  83. this.year = this.date.getFullYear();
  84. this.month = this.date.getMonth();
  85.  
  86.  
  87. this.colors = {
  88. "cur_word"      : "#FFFFFF", //当日日期文字颜色
  89. "cur_bg"        : "#83A6F4", //当日日期单元格背影色
  90. "sel_bg"        : "#FFCCCC", //已被选择的日期单元格背影色
  91. "sun_word"      : "#FF0000", //星期天文字颜色
  92. "sat_word"      : "#0000FF", //星期六文字颜色
  93. "td_word_light" : "#333333", //单元格文字颜色
  94. "td_word_dark" : "#CCCCCC", //单元格文字暗色
  95. "td_bg_out"     : "#EFEFEF", //单元格背影色
  96. "td_bg_over"    : "#FFCC00", //单元格背影色
  97. "tr_word"       : "#FFFFFF", //日历头文字颜色
  98. "tr_bg"         : "#666666", //日历头背影色
  99. "input_border" : "#CCCCCC", //input控件的边框颜色
  100. "input_bg"      : "#EFEFEF"   //input控件的背影色
  101. }
  102.  
  103. this.draw();
  104. this.bindYear();
  105. this.bindMonth();
  106. this.changeSelect();
  107. this.bindData();
  108. }
  109.  
  110. /**//*
  111. * 日历类属性(语言包,可自由扩展)
  112. */
  113. Calendar.language ={
  114. "year"   : [[""], [""]],
  115. "months" : [["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
  116.         ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]
  117.          ],
  118. "weeks" : [["日","一","二","三","四","五","六"],
  119.         ["SUN","MON","TUR","WED","THU","FRI","SAT"]
  120.          ],
  121. "clear" : [["清空"], ["CLS"]],
  122. "today" : [["今天"], ["TODAY"]],
  123. "close" : [["关闭"], ["CLOSE"]]
  124. }
  125.  
  126. Calendar.prototype.draw = function(){
  127. calendar = this;
  128.  
  129. var mvAry = [];
  130. mvAry[mvAry.length] = ' <div name="calendarForm" style="margin: 0px;">';
  131. mvAry[mvAry.length] = '    <table width="100%" border="0" cellpadding="0" cellspacing="1">';
  132. mvAry[mvAry.length] = '      <tr>';
  133. mvAry[mvAry.length] = '        <th align="left" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="prevMonth" type="button" id="prevMonth" value="&lt;" /></th>';
  134. mvAry[mvAry.length] = '        <th align="center" width="98%" nowrap="nowrap"><select name="calendarYear" id="calendarYear" style="font-size:12px;"></select><select name="calendarMonth" id="calendarMonth" style="font-size:12px;"></select></th>';
  135. mvAry[mvAry.length] = '        <th align="right" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="nextMonth" type="button" id="nextMonth" value="&gt;" /></th>';
  136. mvAry[mvAry.length] = '      </tr>';
  137. mvAry[mvAry.length] = '    </table>';
  138. mvAry[mvAry.length] = '    <table id="calendarTable" width="100%" style="border:0px solid #CCCCCC;background-color:#FFFFFF" border="0" cellpadding="3" cellspacing="1">';
  139. mvAry[mvAry.length] = '      <tr>';
  140. for(var i = 0; i < 7; i++){
  141.     mvAry[mvAry.length] = '      <th style="font-weight:normal;background-color:' + calendar.colors["tr_bg"] + ';color:' + calendar.colors["tr_word"] + ';">' + Calendar.language["weeks"][this.lang][i] + '</th>';
  142. }
  143. mvAry[mvAry.length] = '      </tr>';
  144. for(var i = 0; i < 6;i++){
  145.     mvAry[mvAry.length] = '    <tr align="center">';
  146.     for(var j = 0; j < 7; j++){
  147.       if (j == 0){
  148.         mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sun_word"] + ';"></td>';
  149.       } else if(j == 6){
  150.         mvAry[mvAry.length] = ' <td style="cursor:default;color:' + calendar.colors["sat_word"] + ';"></td>';
  151.       } else{
  152.         mvAry[mvAry.length] = ' <td style="cursor:default;"></td>';
  153.       }
  154.     }
  155.     mvAry[mvAry.length] = '    </tr>';
  156. }
  157. mvAry[mvAry.length] = '      <tr style="background-color:' + calendar.colors["input_bg"] + ';">';
  158. mvAry[mvAry.length] = '        <th colspan="2"><input name="calendarClear" type="button" id="calendarClear" value="' + Calendar.language["clear"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>';
  159. mvAry[mvAry.length] = '        <th colspan="3"><input name="calendarToday" type="button" id="calendarToday" value="' + Calendar.language["today"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>';
  160. mvAry[mvAry.length] = '        <th colspan="2"><input name="calendarClose" type="button" id="calendarClose" value="' + Calendar.language["close"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>';
  161. mvAry[mvAry.length] = '      </tr>';
  162. mvAry[mvAry.length] = '    </table>';
  163. mvAry[mvAry.length] = ' </div>';
  164. this.panel.innerHTML = mvAry.join("");
  165.  
  166. var obj = this.getElementById("prevMonth");
  167. obj.onclick = function (){calendar.goPrevMonth(calendar);}
  168. obj.onblur = function (){calendar.onblur();}
  169. this.prevMonth= obj;
  170.  
  171. obj = this.getElementById("nextMonth");
  172. obj.onclick = function (){calendar.goNextMonth(calendar);}
  173. obj.onblur = function (){calendar.onblur();}
  174. this.nextMonth= obj;
  175.  
  176.  
  177. obj = this.getElementById("calendarClear");
  178. obj.onclick = function (){calendar.dateControl.value = "";calendar.hide();}
  179. this.calendarClear = obj;
  180.  
  181. obj = this.getElementById("calendarClose");
  182. obj.onclick = function (){calendar.hide();}
  183. this.calendarClose = obj;
  184.  
  185. obj = this.getElementById("calendarYear");
  186. obj.onchange = function (){calendar.update(calendar);}
  187. obj.onblur = function (){calendar.onblur();}
  188. this.calendarYear = obj;
  189.  
  190. obj = this.getElementById("calendarMonth");
  191. with(obj)
  192. {
  193.     onchange = function (){calendar.update(calendar);}
  194.     onblur = function (){calendar.onblur();}
  195. }this.calendarMonth = obj;
  196.  
  197. obj = this.getElementById("calendarToday");
  198. obj.onclick = function (){
  199.     var today = new Date();
  200.     calendar.date = today;
  201.     calendar.year = today.getFullYear();
  202.     calendar.month = today.getMonth();
  203.     calendar.changeSelect();
  204.     calendar.bindData();
  205.     calendar.dateControl.value = today.format(calendar.dateFormatStyle);
  206.     calendar.hide();
  207. }
  208. this.calendarToday = obj;
  209. }
  210.  
  211. //年份下拉框绑定数据
  212. Calendar.prototype.bindYear = function(){
  213. var cy = this.calendarYear;
  214. cy.length = 0;
  215. for (var i = this.beginYear; i <= this.endYear; i++){
  216.     cy.options[cy.length] = new Option(i + Calendar.language["year"][this.lang], i);
  217. }
  218. }
  219.  
  220. //月份下拉框绑定数据
  221. Calendar.prototype.bindMonth = function(){
  222. var cm = this.calendarMonth;
  223. cm.length = 0;
  224. for (var i = 0; i < 12; i++){
  225.     cm.options[cm.length] = new Option(Calendar.language["months"][this.lang][i], i);
  226. }
  227. }
  228.  
  229. //向前一月
  230. Calendar.prototype.goPrevMonth = function(e){
  231. if (this.year == this.beginYear && this.month == 0){return;}
  232. this.month--;
  233. if (this.month == -1){
  234.     this.year--;
  235.     this.month = 11;
  236. }
  237. this.date = new Date(this.year, this.month, 1);
  238. this.changeSelect();
  239. this.bindData();
  240. }
  241.  
  242. //向后一月
  243. Calendar.prototype.goNextMonth = function(e){
  244. if (this.year == this.endYear && this.month == 11){return;}
  245. this.month++;
  246. if (this.month == 12){
  247.     this.year++;
  248.     this.month = 0;
  249. }
  250. this.date = new Date(this.year, this.month, 1);
  251. this.changeSelect();
  252. this.bindData();
  253. }
  254.  
  255. //改变SELECT选中状态
  256. Calendar.prototype.changeSelect = function(){
  257. var cy = this.calendarYear;
  258. var cm = this.calendarMonth;
  259. for (var i= 0; i < cy.length; i++){
  260.     if (cy.options[i].value == this.date.getFullYear()){
  261.       cy[i].selected = true;
  262.       break;
  263.     }
  264. }
  265. for (var i= 0; i < cm.length; i++){
  266.     if (cm.options[i].value == this.date.getMonth()){
  267.       cm[i].selected = true;
  268.       break;
  269.     }
  270. }
  271. }
  272.  
  273. //更新年、月
  274. Calendar.prototype.update = function (e){
  275. this.year = e.calendarYear.options[e.calendarYear.selectedIndex].value;
  276. this.month = e.calendarMonth.options[e.calendarMonth.selectedIndex].value;
  277. this.date = new Date(this.year, this.month, 1);
  278. this.changeSelect();
  279. this.bindData();
  280. }
  281.  
  282. //绑定数据到月视图
  283. Calendar.prototype.bindData = function (){
  284. var calendar = this;
  285. var dateArray = this.getMonthViewArray(this.date.getFullYear(), this.date.getMonth());
  286. var tds = this.getElementById("calendarTable").getElementsByTagName("td");
  287. for(var i = 0; i < tds.length; i++){
  288. tds[i].style.backgroundColor = calendar.colors["td_bg_out"];
  289.     tds[i].onclick = function () {return;}
  290.     tds[i].onmouseover = function () {return;}
  291.     tds[i].onmouseout = function () {return;}
  292.     if (i > dateArray.length - 1) break;
  293.     tds[i].innerHTML = dateArray[i];
  294.     if (dateArray[i] != "&nbsp;"){
  295.       tds[i].onclick = function () {
  296.         if (calendar.dateControl != null){
  297.           calendar.dateControl.value = new Date(calendar.date.getFullYear(),
  298.                                                 calendar.date.getMonth(),
  299.                                                 this.innerHTML).format(calendar.dateFormatStyle);
  300.         }
  301.         calendar.hide();
  302.       }
  303.       tds[i].onmouseover = function () {
  304.         this.style.backgroundColor = calendar.colors["td_bg_over"];
  305.       }
  306.       tds[i].onmouseout = function () {
  307.         this.style.backgroundColor = calendar.colors["td_bg_out"];
  308.       }
  309.       if (new Date().format(calendar.dateFormatStyle) ==
  310.           new Date(calendar.date.getFullYear(),
  311.                    calendar.date.getMonth(),
  312.                    dateArray[i]).format(calendar.dateFormatStyle)) {
  313.         tds[i].style.backgroundColor = calendar.colors["cur_bg"];
  314.         tds[i].onmouseover = function () {
  315.           this.style.backgroundColor = calendar.colors["td_bg_over"];
  316.         }
  317.         tds[i].onmouseout = function () {
  318.           this.style.backgroundColor = calendar.colors["cur_bg"];
  319.         }
  320.       }//end if
  321.       
  322.       //设置已被选择的日期单元格背影色
  323.       if (calendar.dateControl != null && calendar.dateControl.value == new Date(calendar.date.getFullYear(),
  324.                    calendar.date.getMonth(),
  325.                    dateArray[i]).format(calendar.dateFormatStyle)) {
  326.         tds[i].style.backgroundColor = calendar.colors["sel_bg"];
  327.         tds[i].onmouseover = function () {
  328.           this.style.backgroundColor = calendar.colors["td_bg_over"];
  329.         }
  330.         tds[i].onmouseout = function () {
  331.           this.style.backgroundColor = calendar.colors["sel_bg"];
  332.         }
  333.       }
  334.     }
  335. }
  336. }
  337.  
  338. //根据年、月得到月视图数据(数组形式)
  339. Calendar.prototype.getMonthViewArray = function (y, m) {
  340. var mvArray = [];
  341. var dayOfFirstDay = new Date(y, m, 1).getDay();
  342. var daysOfMonth = new Date(y, m + 1, 0).getDate();
  343. for (var i = 0; i < 42; i++) {
  344.     mvArray[i] = "&nbsp;";
  345. }
  346. for (var i = 0; i < daysOfMonth; i++){
  347.     mvArray[i + dayOfFirstDay] = i + 1;
  348. }
  349. return mvArray;
  350. }
  351.  
  352. //扩展 document.getElementById(id) 多浏览器兼容性 from meizz tree source
  353. Calendar.prototype.getElementById = function(id){
  354. if (typeof(id) != "string" || id == "") return null;
  355. if (document.getElementById) return document.getElementById(id);
  356. if (document.all) return document.all(id);
  357. try {return eval(id);} catch(e){ return null;}
  358. }
  359.  
  360. //扩展 object.getElementsByTagName(tagName)
  361. Calendar.prototype.getElementsByTagName = function(object, tagName){
  362. if (document.getElementsByTagName) return document.getElementsByTagName(tagName);
  363. if (document.all) return document.all.tags(tagName);
  364. }
  365.  
  366. //取得HTML控件绝对位置
  367. Calendar.prototype.getAbsPoint = function (e){
  368. var x = e.offsetLeft;
  369. var y = e.offsetTop;
  370. while(e = e.offsetParent){
  371.     x += e.offsetLeft;
  372.     y += e.offsetTop;
  373. }
  374. return {"x": x, "y": y};
  375. }
  376.  
  377. //显示日历
  378. Calendar.prototype.show = function (dateObj, popControl) {
  379. if (dateObj == null){
  380.     throw new Error("arguments[0] is necessary")
  381. }
  382. this.dateControl = dateObj;
  383.  
  384. this.date = (dateObj.value.length > 0) ? new Date(dateObj.value.toDate(this.dateFormatStyle)) : new Date() ;//若为空则显示当前月份
  385. this.year = this.date.getFullYear();
  386. this.month = this.date.getMonth();
  387. this.changeSelect();
  388. this.bindData();
  389. if (popControl == null){
  390.     popControl = dateObj;
  391. }
  392. var xy = this.getAbsPoint(popControl);
  393. this.panel.style.left = xy.x -25 + "px";
  394. this.panel.style.top = (xy.y + dateObj.offsetHeight) + "px";
  395.  
  396. this.panel.style.display = "";
  397. this.container.style.display = "";
  398.  
  399. dateObj.onblur = function(){calendar.onblur();}
  400. this.container.onmouseover = function(){isFocus=true;}
  401. this.container.onmouseout = function(){isFocus=false;}
  402. }
  403.  
  404. //隐藏日历
  405. Calendar.prototype.hide = function() {
  406. this.panel.style.display = "none";
  407. this.container.style.display = "none";
  408. isFocus=false;
  409. }
  410.  
  411. //焦点转移时隐藏日历
  412. Calendar.prototype.onblur = function() {
  413.     if(!isFocus){this.hide();}
  414. }
  415. document.write('<div id="ContainerPanel" style="display:none;"><div id="calendarPanel" style="position: absolute;display: none;z-index: 9999;');
  416. document.write('background-color: #FFFFFF;border: 1px solid #CCCCCC;width:175px;font-size:12px;margin-left:25px;"></div>');
  417. if(document.all)
  418. {
  419. document.write('<iframe style="position:absolute;z-index:2000;width:expression(this.previousSibling.offsetWidth);');
  420. document.write('height:expression(this.previousSibling.offsetHeight);');
  421. document.write('left:expression(this.previousSibling.offsetLeft);top:expression(this.previousSibling.offsetTop);');
  422. document.write('display:expression(this.previousSibling.style.display);" scrolling="no" frameborder="no"></iframe>');
  423. }
  424. document.write('</div>');
  425. //-->

然后,在你需要日历控件的页面中调用就可以了,例如我有一张页面aa.html,需要使用日历控件,只需要加入:

  1. <script src="Calendar.js" type="text/javascript" language="javascript"></script>
  2. <input name="txtDate" type="text" style="padding-left:5px;" size="10" id="txtDate" onclick="SelectDate(this)" readonly="readonly" />

打开aa.html,点击文本框,日历控件便会出现,点击一个日期后,日历控件消失,文本框出现了你选择的日期,而且该日历控件对于最高年限和最低年限可以自行修改,是不是很方便呢~

相关日志

Leave a comment

您必须 登录 后才能发表留言。

无分类


无分类


无分类


无分类


无分类

无分类


无分类


无分类


无分类


无分类


无分类

无分类