利用JavaScript编写一个日历表
时间: 2024-05-12 09:20:18 浏览: 15
以下是一个简单的JavaScript日历表代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Calendar</title>
<style>
table {
border-collapse: collapse;
margin: auto;
}
th, td {
padding: 10px;
text-align: center;
border: 1px solid black;
}
th {
background-color: #ccc;
}
td:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<h1>JavaScript Calendar</h1>
<table>
<thead>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody id="calendar-body">
</tbody>
</table>
<script>
// Get the current date
var today = new Date();
// Get the year and month
var year = today.getFullYear();
var month = today.getMonth() + 1; // January is 0
// Get the number of days in the current month
var daysInMonth = new Date(year, month, 0).getDate();
// Get the first day of the current month
var firstDayOfMonth = new Date(year, month-1, 1).getDay(); // Sunday is 0
// Create the calendar table
var calendarTable = document.getElementById("calendar-body");
var date = 1;
for (var i = 0; i < 6; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 7; j++) {
if (i === 0 && j < firstDayOfMonth) {
var cell = document.createElement("td");
var cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
}
else if (date > daysInMonth) {
break;
}
else {
var cell = document.createElement("td");
var cellText = document.createTextNode(date);
cell.appendChild(cellText);
row.appendChild(cell);
date++;
}
}
calendarTable.appendChild(row);
}
</script>
</body>
</html>
```
该代码将生成一个简单的日历表,显示当前月份的日期。您可以根据需要自定义样式和功能。