js实现日历
JavaScript 实现日历的方法
使用原生 JavaScript 创建日历
通过 Date 对象和 DOM 操作可以构建一个简单的日历。以下是一个基础实现示例:
function createCalendar(year, month, elementId) {
const date = new Date(year, month - 1, 1);
const daysInMonth = new Date(year, month, 0).getDate();
const firstDay = date.getDay();
let calendar = '<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++) {
calendar += '<td></td>';
}
for (let day = 1; day <= daysInMonth; day++) {
if ((day + firstDay - 1) % 7 === 0) {
calendar += '</tr><tr>';
}
calendar += `<td>${day}</td>`;
}
calendar += '</tr></table>';
document.getElementById(elementId).innerHTML = calendar;
}
// 调用示例
createCalendar(2023, 11, 'calendar-container');
使用第三方库
对于更复杂的日历需求,可以考虑使用成熟的 JavaScript 日历库:

- FullCalendar:功能丰富的日历组件,支持事件拖拽、资源视图等
- Flatpickr:轻量级的日期选择器
- Date-fns:日期处理工具库,可配合日历显示使用
响应式日历实现
结合 CSS Grid 或 Flexbox 实现响应式布局:
.calendar {
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.calendar-header {
font-weight: bold;
text-align: center;
}
.calendar-day {
border: 1px solid #ddd;
padding: 5px;
min-height: 50px;
}
添加事件功能
为日历日期添加点击事件处理:

document.querySelectorAll('.calendar-day').forEach(day => {
day.addEventListener('click', () => {
console.log('Selected date:', day.textContent);
});
});
国际化支持
使用 Intl.DateTimeFormat 处理不同地区的日期格式:
const formatter = new Intl.DateTimeFormat('zh-CN', {
weekday: 'short',
year: 'numeric',
month: 'long',
day: 'numeric'
});
性能优化建议
对于大型日历应用:
- 使用虚拟滚动技术只渲染可见日期
- 避免频繁的 DOM 操作,使用文档片段批量更新
- 对日期计算进行缓存
以上方法可以根据具体需求组合使用,构建功能完善的日历组件。





