最近看社区上面或者其他的网站上都有一个签到并且附带签到日历便想着自己动手做一下
1.先构思出一个原型,为了方便我使用的table做为容器. 我是参照win10日历准备画一个这样的东西 一共 7行7列 2.有了思绪后,我们需要获得当月第一天是周几
function getWeekOneDay(){ var date=new Date(); date=new Date(date.setDate(1)) return date.getDay();//0-6 }用这段函数可以获得周一到周日 返回一个数字 0 周日 1 周一 2 周二 3 周三 4 周四 5 周五 6 周六
因为一些原因我不太喜欢周日用0因为或许使用0则会使用更多的逻辑判断这里我把周日换成了7 var week;
if(getWeekOneDay()==0){ week=7; }3.我需要把每月的一号位置确定 其余的部分补空格 7 6 6 5 5 4 4 3 3 2 2 1 1 0 我们的公式就是 当天-1=需要的空格数
剩下的就是一些拼接和循环的技巧,请自行领悟 贴出源代码
;(function(undefined) { "use strict" var _global; var calendar = { init: function initCalendar(selector){ var table="<table>"; table+="<tr class='week'><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td><td>日</td></tr>"; table+="<tr>"; var oneDayWeek=getWeekOneDay(); var weekRowLastNum=0; if(oneDayWeek==0){oneDayWeek=7;} var nbspCount=oneDayWeek-1; for (var j=0;j<nbspCount;j++){ table+="<td class='nbsp'> </td>"; } for(var k=0;k<7-nbspCount;k++){ if(!((k+1)==getDay())){ table+="<td>"+(k+1)+"</td>"; }else{ table+="<td style='background-color: rgba(148, 113, 255, 0.56);'>"+(k+1)+"</td>" } weekRowLastNum=(k+1); } table+="</tr>" table+="<tr>"; for(var x=weekRowLastNum;x<getCountDays();x++){ if(!((x+1)==getCountDays())){ if(getDay(x+1)){ table+="<td class='day' style='background-color: rgba(148, 113, 255, 0.56);'>"+(x+1)+"</td>"; }else{ table+="<td>"+(x+1)+"</td>"; } }else{ if(getDay(x+1)){ table+="<td class='day' class='last' style='background-color: rgba(148, 113, 255, 0.56);'>"+(x+1)+"</td>"; } else{ table+="<td class='last'>"+(x+1)+"</td>"; } } if(x%7==0){ table+="</tr>"; table+="<tr>"; } } table+="</tr>"; $(selector).append(table); var parent=$(".last").parent(); for(var i=0;i<7-$(".last").parent.length;i++){ parent.append("<td> </td>"); } }, title: function setCalendarTitle(selector){ var date = new Date(); $(selector).append(date.getFullYear()+"年 "+"/"+date.getMonth()+"月 "+"/"+ date.getDate()+"日"+" "+"社区签到板"); } } function getDay(day) { var date = new Date(); return (date.getDate()==day); } function getCountDays() { var date = new Date(); var curMonth = date.getMonth(); date.setMonth(curMonth + 1); date.setDate(0); return date.getDate(); } function getWeekOneDay(){ var date=new Date(); date=new Date(date.setDate(1)) return date.getDay();//0-6 } _global = (function(){ return this || (0, eval)('this'); }()); if (typeof module !== "undefined" && module.exports) { module.exports = calendar; } else if (typeof define === "function" && define.amd) { define(function(){return calendar;}); } else { !('calendar' in _global) && (_global.calendar = calendar); } }());调用
$(()=>{ calendar.title(".title"); calendar.init(".test");});