在“不使用任何第三方库的情况下,使用HTML / CSS / JS设计日历”时,有人问我这个问题。
我遇到了这个解决方案。但是我想知道是否有更好的(或可读的)方法来设计该系统?我很难理解这个解决方案,并且正在寻找更好的解决方案来学习此问题。
解决方案:
window.onload = function() {
var d = new Date();
var month_name = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var month = d.getMonth(); //0-11
var year = d.getFullYear(); //2014
var first_date = month_name[month] + " " + 1 + " " + year;
//September 1 2018
var tmp = new Date(first_date).toDateString();
//Mon Sep 01 2018 ...
var first_day = tmp.substring(0, 3); //Mon
var day_name = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var day_no = day_name.indexOf(first_day); //1
var days = new Date(year, month + 1, 0).getDate(); //30
//Tue Sep 30 2018 ...
var calendar = get_calendar(day_no, days);
document.getElementById("calendar-month-year").innerHTML = month_name[month] + " " + year;
document.getElementById("calendar-dates").appendChild(calendar);
}
function get_calendar(day_no, days) {
var table = document.createElement('table');
var tr = document.createElement('tr');
//row for the day letters
for (var c = 0; c <= 6; c++) {
var td = document.createElement('td');
td.innerHTML = "SMTWTFS" [c];
tr.appendChild(td);
}
table.appendChild(tr);
//create 2nd row
tr = document.createElement('tr');
var c;
for (c = 0; c <= 6; c++) {
if (c == day_no) {
break;
}
var td = document.createElement('td');
td.innerHTML = "";
tr.appendChild(td);
}
var count = 1;
for (; c <= 6; c++) {
var td = document.createElement('td');
td.innerHTML = count;
count++;
tr.appendChild(td);
}
table.appendChild(tr);
//rest of the date rows
for (var r = 3; r <= 7; r++) {
tr = document.createElement('tr');
for (var c = 0; c <= 6; c++) {
if (count > days) {
table.appendChild(tr);
return table;
}
var td = document.createElement('td');
td.innerHTML = count;
count++;
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
#calendar-container {
padding: 10px;
width: 210px;
height: 240px;
text-align: center;
border: 1px solid #eee;
border-radius: 10px;
font-size: 16px;
font-family: Arial;
background-image: linear-gradient(#fff, #d3d3d3);
}
#calendar-container>div {
padding: 0;
margin-bottom: 10px;
}
#calendar-month-year {
margin: 5px;
}
#calendar-dates>table>tr>td {
padding: 5px;
}
<section id="calendar-container">
<article id="calendar-header">
<span id="calendar-month-year"></span>
</article>
<article id="calendar-dates"></article>
</section>