项目需求,页面展示当前月的日历,每天的框里面放上用电量,可以按月查询,日历展示如下:
showCode:
// html
<div class="myClander" ref="customeCalender">
</div>
// js
var weekday = new Array("星期天","星期一","星期二","星期三","星期四","星期五","星期六"); // 星期
var monthname = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); // 月
var monthdays = new Array(31,28,31,30,31,30,31,31,30,31,30,31); // 每月天数
// 假的电量:后台返回数据
var currentMouth = []
for (var p = 1; p <= 31 ;p ++) {
currentMouth.push(p)
}
var mydate = new Date(); //var mydate = new Date(2019,10); 查询时候 传入指定日期
var myyear = mydate.getFullYear();
var mymouth = mydate.getMonth();
var myday = mydate.getDate(); //获取当前日期
var myweek = mydate.getDay(); //获取当前星期几
if(myyear%4 == 0 && myyear%100 == 0 || myyear%400 == 0){ //判断闰年
mouthdays[1]=29;
}
mydate.setDate(1); // 设置当月为1号
var m = mydate.getDay();//获取当前月1号星期几
var personalCalder = document.getElementsByClassName("myClander")[0]
var html = ''
html += "<table width='600' style='color:#fff;font-size:12px' border='1'>"
// 当前日期title
html += "<tr align='center'><td colspan='7' >"+myyear+"年"+(++mymouth)+"月"+myday+"日"+"<span style='padding-left:20px;'>"+ monthname[mymouth-1] +"月</span></td></tr>"
var n = 1;
mymouth --;
// 渲染 第一行 星期几 表头
html += '<tr>'
for(var i = 0;i < 7; i++) {
html += '<td>'+ weekday[i] +'</td>'
}
// 日期
html += '</tr>'
for(var i = 0;i < 5; i++) {
if(m > 0){ // 如果本月1号不是星期日,
html += '<tr>'
for(var j = 0;j < m; j++) { // 则在这行第一个单元格为空
html += '<td> </td>'
}
for(var k = m;k < 7; k++) {
if(n == myday) { // 本月当天日期渲染红色
html += '<td>'+
'<div style="color:red;font-size:12px">'+ n +'</div>' +
'<div>电量:'+ currentMouth[n-1] +'</div>'
+'</td>'
} else { // 本月不是当天日期渲染绿色
html += '<td>'+
'<div style="color:green;font-size:12px">'+ n +'</div>' +
'<div style="color:#ccc">电量:'+ currentMouth[n-1] +'</div>'
+'</td>'
}
n++
}
html += '</tr>'
m = 0; // 第一行(除表头外)渲染完后,将星期归为星期天,从0开始
}
if(m == 0){
html += '<tr>'
for(var k = 0; k < 7; k++) {
if(n > monthdays[mymouth]){ // 如果渲染大于本月天数,则这个单元格为空
html += '<td> </td>'
} else {
if(n == myday) { // 本月当天日期渲染红色
html += '<td>'+
'<div style="color:red;font-size:12px">'+ n +'</div>' +
'<div>电量:'+ currentMouth[n-1] +'</div>'
+'</td>'
} else {
html += '<td>'+
'<div style="color:green;font-size:12px">'+ n +'</div>' +
'<div style="color:#ccc">电量:'+ currentMouth[n-1] +'</div>'
+'</td>'
}
n++;
}
}
html += '</tr>'
}
}
// 计算总的用电数
var sum = currentMouth.reduce((prev,cur,index,array) =>{
return prev + cur
})
html += '<tr>'+
'<td colspan="7" align="center">月累计用电:'+ sum +'</td>'
+'</tr>'
personalCalder.innerHTML = html