js实现日历方法
实现日历的基本思路
日历的核心功能包括显示当月日期、切换月份、高亮当前日期等。通过JavaScript动态生成HTML结构,结合CSS样式实现交互效果。
获取当前日期信息
使用Date对象获取当前年份、月份和日期,为后续生成日历提供基础数据。
const date = new Date();
let currentYear = date.getFullYear();
let currentMonth = date.getMonth();
生成月份日历
计算当月天数及首日星期,生成日期表格。需要考虑跨月日期的显示。
function generateCalendar(year, month) {
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
let dates = [];
// 填充上月剩余日期
for (let i = 0; i < firstDay; i++) {
dates.push(null);
}
// 填充当月日期
for (let i = 1; i <= daysInMonth; i++) {
dates.push(i);
}
return dates;
}
渲染日历界面
将生成的日期数组转换为HTML元素,创建表格布局。
function renderCalendar(dates) {
const calendarBody = document.getElementById('calendar-body');
calendarBody.innerHTML = '';
let row = document.createElement('tr');
dates.forEach((date, index) => {
if (index % 7 === 0 && index !== 0) {
calendarBody.appendChild(row);
row = document.createElement('tr');
}
const cell = document.createElement('td');
cell.textContent = date || '';
row.appendChild(cell);
});
calendarBody.appendChild(row);
}
添加月份切换功能
实现向前和向后翻页按钮,更新日历显示。
document.getElementById('prev-month').addEventListener('click', () => {
currentMonth--;
if (currentMonth < 0) {
currentMonth = 11;
currentYear--;
}
updateCalendar();
});
document.getElementById('next-month').addEventListener('click', () => {
currentMonth++;
if (currentMonth > 11) {
currentMonth = 0;
currentYear++;
}
updateCalendar();
});
function updateCalendar() {
const dates = generateCalendar(currentYear, currentMonth);
renderCalendar(dates);
document.getElementById('month-year').textContent =
`${currentYear}年 ${currentMonth + 1}月`;
}
高亮当前日期
在日历中突出显示今天的日期,增强用户体验。
function highlightToday() {
const today = new Date();
if (today.getFullYear() === currentYear && today.getMonth() === currentMonth) {
const cells = document.querySelectorAll('#calendar-body td');
cells.forEach(cell => {
if (parseInt(cell.textContent) === today.getDate()) {
cell.classList.add('today');
}
});
}
}
完整实现示例
结合HTML和CSS,以下是完整日历实现的核心代码:
<div class="calendar">
<div class="header">
<button id="prev-month">上个月</button>
<h2 id="month-year"></h2>
<button id="next-month">下个月</button>
</div>
<table>
<thead>
<tr>
<th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th>
</tr>
</thead>
<tbody id="calendar-body"></tbody>
</table>
</div>
// 初始化日历
document.addEventListener('DOMContentLoaded', () => {
updateCalendar();
highlightToday();
});
日期选择功能扩展
为日历添加点击选择日期的交互功能,记录用户选择的日期。
document.getElementById('calendar-body').addEventListener('click', (e) => {
if (e.target.tagName === 'TD' && e.target.textContent) {
const selected = document.querySelector('.selected');
if (selected) selected.classList.remove('selected');
e.target.classList.add('selected');
console.log(`选中日期: ${currentYear}-${currentMonth+1}-${e.target.textContent}`);
}
});
响应式布局优化
通过CSS媒体查询确保日历在不同设备上都能正常显示。
@media (max-width: 600px) {
.calendar {
width: 100%;
}
td {
padding: 5px;
font-size: 14px;
}
}






