js实现日历
实现日历的基本思路
使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。
获取当前日期信息
通过Date对象获取当前年份、月份和日期:
const date = new Date();
const currentYear = date.getFullYear();
const currentMonth = date.getMonth();
const currentDay = date.getDate();
计算月份天数
使用Date对象计算某个月份的天数:

function getDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
计算月份起始星期
确定月份第一天是星期几:
function getFirstDayOfMonth(year, month) {
return new Date(year, month, 1).getDay();
}
生成日历表格
创建表格并填充日期单元格:

function generateCalendar(year, month) {
const daysInMonth = getDaysInMonth(year, month);
const firstDay = getFirstDayOfMonth(year, month);
let date = 1;
let html = '<table><tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr><tr>';
// 填充空白单元格
for (let i = 0; i < firstDay; i++) {
html += '<td></td>';
}
// 填充日期单元格
for (let i = firstDay; i < 7; i++) {
html += `<td>${date}</td>`;
date++;
}
html += '</tr>';
// 填充剩余行
while (date <= daysInMonth) {
html += '<tr>';
for (let i = 0; i < 7 && date <= daysInMonth; i++) {
html += `<td>${date}</td>`;
date++;
}
html += '</tr>';
}
html += '</table>';
return html;
}
添加月份切换功能
实现月份切换按钮和逻辑:
let currentYear = new Date().getFullYear();
let currentMonth = new Date().getMonth();
function updateCalendar() {
document.getElementById('calendar').innerHTML = generateCalendar(currentYear, currentMonth);
document.getElementById('month-year').textContent = `${currentYear}年 ${currentMonth + 1}月`;
}
document.getElementById('prev').addEventListener('click', () => {
currentMonth--;
if (currentMonth < 0) {
currentMonth = 11;
currentYear--;
}
updateCalendar();
});
document.getElementById('next').addEventListener('click', () => {
currentMonth++;
if (currentMonth > 11) {
currentMonth = 0;
currentYear++;
}
updateCalendar();
});
完整HTML结构
配套的HTML基础结构:
<div id="calendar-container">
<div id="header">
<button id="prev">上个月</button>
<h2 id="month-year"></h2>
<button id="next">下个月</button>
</div>
<div id="calendar"></div>
</div>
样式美化建议
添加基本CSS样式增强视觉效果:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
#header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
高级功能扩展
- 添加日期点击事件处理
- 实现日程标记功能
- 支持周视图切换
- 添加节假日特殊样式
- 实现日期范围选择
这些基础代码提供了日历的核心功能,可以根据需求进一步扩展和完善。






