function Calendar(container, year, month) { this.year = year; this.month = month; this.html = html; this.el = document.createElement("table"); this.el.className = 'calendar'; this.el.innerHTML = this.html(); container.appendChild(this.el); this.el.addEventListener('click', event => { var el = event.target; var isPre = el.classList.contains('pre'); var isNext = el.classList.contains('next'); if (!isPre && !isNext) return; if (isPre) { if (this.month === 1) { this.year--; this.month = 12; } else { this.month--; } } else { if (this.month === 12) { this.year++; this.month = 1; } else { this.month++; } } this.el.innerHTML = this.html(); }); function html() { var date = new Date(); var year = +this.year || 0; var month = (+this.month || 0) - 1; var day = date.getDate(); let arr1 = [31,28,31,30,31,30,31,31,30,31,30,31] //平年 let arr2 = [31,29,31,30,31,30,31,31,30,31,30,31] //闰年 let thead = document.createElement("thead"); let tbody = document.createElement("tbody"); let thead_th = `<tr><th class="pre"><</th><th colspan="5" class="date">${this.year}.${this.month.toString().padStart(2, "0")}</th><th class="next">></th></tr> <tr><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th><th>日</th></tr>` thead.innerHTML = thead_th; let n; // 月份天数 if (this.year % 4 == 0 && this.year % 400 !== 0) { n = arr2[month]; } else { n = arr1[month]; } let startDay = (new Date(`${this.year} ${this.month} 1`)).getDay() - 1; if (startDay == -1) startDay = 6; let tr = document.createElement("tr"); let days = 1; for (let i = 0; i < startDay; i++) { tr.innerHTML += `<td></td>` } for (let i = startDay; i < n+startDay; i++) { if (i != 0 && i % 7 == 0) { tbody.appendChild(tr); tr = document.createElement("tr"); } let str; if (days == day && this.year == date.getFullYear() && this.month-1 == date.getMonth() ) { str = `<td class="current">${days++}</td>` } else { str = `<td>${days++}</td>`; } tr.innerHTML += str; if (i+1 == n+startDay) { for (let j = 0; j < (7 - i%7)-1; j++) { tr.innerHTML += `<td></td>`; } tbody.appendChild(tr); } } return toTagStr(thead)+toTagStr(tbody); } function toTagStr(el) { let tagName = el.tagName; let text = el.innerHTML; let res = `<${tagName}>${text}</${tagName}>`; return res; } } //只上传了代码, 写的有点乱 见谅
全部评论
(0) 回帖