js 万年历
时间: 2023-07-12 11:18:45 浏览: 49
好的,以下是一个简单的 JavaScript 实现万年历的代码:
```javascript
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function getDaysInMonth(year, month) {
if (month === 2) {
return isLeapYear(year) ? 29 : 28;
} else if ([4, 6, 9, 11].includes(month)) {
return 30;
} else {
return 31;
}
}
function getDayOfWeek(year, month, day) {
const days = ["日", "一", "二", "三", "四", "五", "六"];
const date = new Date(year, month - 1, day);
return days[date.getDay()];
}
function getCalendar(year, month) {
const daysInMonth = getDaysInMonth(year, month);
const firstDayOfWeek = getDayOfWeek(year, month, 1);
const calendar = [];
let week = [null, null, null, null, null, null, null];
for (let day = 1, i = 0; day <= daysInMonth; day++, i++) {
week[i] = day;
if (getDayOfWeek(year, month, day) === "六" || day === daysInMonth) {
calendar.push(week);
week = [null, null, null, null, null, null, null];
i = -1;
}
}
return { calendar, firstDayOfWeek };
}
function formatMonth(month) {
return month < 10 ? "0" + month : month;
}
function createCalendarTable(year, month) {
const { calendar, firstDayOfWeek } = getCalendar(year, month);
let table = "<table>";
table += "<tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>";
for (let week of calendar) {
table += "<tr>";
for (let day of week) {
if (day === null) {
table += "<td></td>";
} else {
table += `<td>${day}</td>`;
}
}
table += "</tr>";
}
table += "</table>";
return table;
}
function createCalendar(year, month) {
const { calendar, firstDayOfWeek } = getCalendar(year, month);
const monthStr = `${year}年${formatMonth(month)}月`;
let calendarHtml = `
<div class="calendar">
<div class="month">${monthStr}</div>
${createCalendarTable(year, month)}
</div>
`;
return calendarHtml;
}
```
使用方法:
```javascript
// 创建 2021 年 10 月的万年历
const calendarHtml = createCalendar(2021, 10);
// 将 HTML 插入到页面中
document.body.innerHTML = calendarHtml;
```
这样就可以在页面上显示出 2021 年 10 月的万年历了。