<meta charset="utf-8">
<div id="calendar"></div>
<script>
/**
* edgesun@126.com
* 20190207
*/
function myCalendar(YEAR,MONTH){
function isLng(num){return /^(0|([1-9]\d*))$/.test(''+num);}
var myDate=new Date(), today={year:myDate.getFullYear(), month:myDate.getMonth(), date:myDate.getDate(), ymd:''}; //当前日期
today.ymd = today.year+ (today.month<9?'0':'')+(today.month+1)+(today.date<10?'0':'')+today.date;
if(isLng(YEAR) && isLng(MONTH)){
if(YEAR<2010 || YEAR>2037){alert('不能再翻啦~');return;}
if(MONTH>11){alert('参数month应该为0到11的整数');return;}
myDate.setFullYear(YEAR, MONTH, 1);
}else{
YEAR = today.year;
MONTH = today.month;
}
var PrevNext=[[0,0],[0,0]]; //依次为上一月的年、月,下一月的年、月
if(MONTH==0){
PrevNext = [[YEAR-1,11],[YEAR,1]];
}else if(MONTH==11){
PrevNext = [[YEAR,10],[YEAR+1,0]];
}else{
PrevNext = [[YEAR,MONTH-1],[YEAR,MONTH+1]];
}
myDate.setDate(1); //当前显示月的第一天
var weekday=myDate.getDay()?myDate.getDay():7; //当前显示月的第一天是星期几(星期天重置为7,即每周最后一天)
myDate.setMonth(MONTH+1);
myDate.setDate(0);
var totalDays = myDate.getDate(); //当前显示月的总天数
var html='<table width="100%" border="1" cellpadding="5" cellspacing="0"><thead><tr><th onclick="myCalendar('+PrevNext[0][0]+','+PrevNext[0][1]+')">上个月</th><th colspan="5">'+YEAR+'年'+(MONTH+1)+'月</th><th onClick="myCalendar('+PrevNext[1][0]+','+PrevNext[1][1]+')">下个月</th></tr><tr><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th>星期六</th><th>星期日</th></tr></th><tbody>';
var n=0, ymd='';
for(var i=1; i<=42; ++i){
if(i%7==1) html+='<tr>';
if(i>=weekday && i<totalDays+weekday){
++n;
ymd=''+YEAR+(MONTH<9?'0':'')+(MONTH+1)+(n<10?'0':'')+n;
html+='<td'+(ymd==today.ymd?' style="background-color:#ddf;"':'')+' data-date="'+ymd+'">'+n+'</td>';
}else{
html+='<td></td>';
}
if(i%7==0){
html+='</tr>';
if(i>=(totalDays+weekday-1))break;
}
}
html+='</tbody></table>';
document.getElementById('calendar').innerHTML=html;
}
myCalendar();
</script>