横長カレンダーを書く jQuery ソース・・・メモ。
moment.js http://momentjs.com/ を使うことにした。jQuery は、2.x系で書いた。
moment-with-locales.js を使う。
/* datetext = yyyy/MM/dd 日付 * predays = 前方日数(datetextの日付を含まないカウント) * afterdays = 後方日数(datetextの日付を含まないカウント) */ var writeCalandarHead = function(datetext, predays, afterdays){ var basedate = moment(datetext, "YYYY/MM/DD"); var dt = moment(datetext, "YYYY/MM/DD"); dt.add(predays * -1 - 1, "days"); var mary = {}; $('thead tr:nth-child(1) th:nth-child(n+2)').remove(); $('thead tr:nth-child(2) th').remove(); var len = predays + afterdays + 1; for(var i=0; i < len; i++){ dt = dt.add(1, "days"); var key = (dt.month()+1) + "月"; mary[key] = mary[key]==undefined ? 1 : mary[key] = mary[key] + 1; var plusclass = ""; if (basedate.diff(dt, "days")==0){ plusclass = ' class="today"'; }else{ var week = dt.format("dddd"); if (week=="Saturday") plusclass = ' class="Saturday"'; if(week=="Sunday") plusclass = ' class="Sunday"'; } $('thead tr:nth-child(2)').append("<th" + plusclass + ">" + dt.date() + "</th>" ); } Object.keys(mary).forEach(function(key){ $('thead tr:nth-child(1)').append('<th colspan="' + mary[key] + '">' + key + '</th>'); }); }; $(function(){ $("input[class='datepicker default']").datepicker({ prevText:"前月", nextText:"翌月", changeMonth: true, changeYear: true, yearRange: '-3:+4', onSelect: function(dateText){ writeCalandarHead(dateText, 5, 20); }, }).datepicker("setDate", moment().format('YYYY/MM/DD')); writeCalandarHead(moment().format('YYYY/MM/DD'), 5, 20); });
HTMLは、、、jquery-2.x と jquery-ui を指定して、、
<input type="text" class="datepicker default" style="width: 70px"> <div> <table> <thead> <tr><th rowspan="2" style="width: 100px">header</th></tr> <tr></tr> </thead> </table> </div>
CSS は、、
.ui-datepicker{ font-size: 80%; } .ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year{ width: auto; } table{ box-sizing: border-box; border-spacing: 0; border-collapse: collapse; white-space: nowrap; font-size: 14px; } th{ border: 1px solid #000000; } tr:nth-child(2) th{ width: 30px; } th.today { background-color: #ffff60; } th.Saturday { background-color: #b3f2ff; } th.Sunday { background-color: #ffb9b3; }
表示すると。