创建一个HTML表格来显示日历。 使用JavaScript来确定当前月份的日期和星期几。 动态填充表格以显示当前月份的每一天。 用特殊样式(如红色)标记今天的日期。
时间: 2024-09-23 14:04:04 浏览: 99
创建一个HTML表格来显示日历,你可以参考以下步骤:
首先,在HTML中设置基础结构:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>日历</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: center;
}
.today {
background-color: #FFA57A; /* 鲜艳的橙色代表今天 */
}
</style>
</head>
<body>
<table id="calendarTable">
<thead>
<tr>
<th>星期</th>
<th></th>
<!-- 从一到七 -->
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<!-- ...以此类推 -->
</tr>
</thead>
<tbody id="days"></tbody>
</table>
<script src="calendar.js"></script>
</body>
</html>
```
接下来,创建`calendar.js`文件来计算并填充表格:
```javascript
// 获取当前日期
function getCurrentDate() {
const today = new Date();
return [today.getDate(), today.getMonth() + 1, today.getFullYear()];
}
// 计算星期几
function getWeekday(date) {
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
return weekdays[date.getDay()];
}
// 动态填充表格
function fillCalendarTable() {
const [dayOfMonth, month, year] = getCurrentDate();
const daysInMonth = new Date(year, month, 0).getDate();
let tbody = document.getElementById('days');
// 清空之前的日期
while (tbody.firstChild) {
tbody.removeChild(tbody.firstChild);
}
for (let i = 1; i <= daysInMonth; i++) {
const tr = document.createElement('tr');
const td = document.createElement('td');
if (i === dayOfMonth) {
td.classList.add('today'); // 标记今天
}
td.textContent = i;
tr.appendChild(td);
// 添加星期信息
td = document.createElement('td');
td.textContent = getWeekday(i);
tr.appendChild(td);
tbody.appendChild(tr);
}
}
// 初始化表格
fillCalendarTable();
```
现在,当你运行此代码时,将会在网页上看到一个显示当前月份的日历表格,今天的日子会被特别标注为鲜艳的橙色。
阅读全文
相关推荐


















