js实现日期表格
实现日期表格的步骤
HTML结构
创建一个基本的HTML结构,包含一个表格元素用于显示日期。

<div id="calendar"></div>
JavaScript逻辑
使用JavaScript动态生成日期表格,通常包括以下功能:

- 获取当前月份的天数
- 确定月份的第一天是星期几
- 生成表格的行和列
function generateCalendar(year, month) {
const calendar = document.getElementById('calendar');
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const daysInMonth = lastDay.getDate();
const startingDay = firstDay.getDay(); // 0 (Sunday) to 6 (Saturday)
let html = '<table>';
html += '<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>';
let date = 1;
for (let i = 0; i < 6; i++) {
if (date > daysInMonth) break;
html += '<tr>';
for (let j = 0; j < 7; j++) {
if (i === 0 && j < startingDay) {
html += '<td></td>';
} else if (date > daysInMonth) {
html += '<td></td>';
} else {
html += `<td>${date}</td>`;
date++;
}
}
html += '</tr>';
}
html += '</table>';
calendar.innerHTML = html;
}
// 调用函数生成当前月份的日历
const currentDate = new Date();
generateCalendar(currentDate.getFullYear(), currentDate.getMonth());
样式调整
通过CSS美化日历表格,使其更易读。
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
功能扩展
- 添加月份切换按钮
- 高亮当前日期
- 支持事件点击
// 示例:高亮当前日期
const currentDay = new Date().getDate();
const cells = document.querySelectorAll('td');
cells.forEach(cell => {
if (cell.textContent == currentDay) {
cell.style.backgroundColor = '#ffcccb';
}
});
通过以上步骤,可以实现一个基本的日期表格,并支持进一步的功能扩展。






