javascript日历
时间: 2023-08-13 20:07:33 浏览: 92
你想了解 JavaScript 实现的日历吗? JavaScript 可以通过 DOM 操作实现动态生成日历的功能。以下是一个简单的 JavaScript 日历实现示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript 日历示例</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: center;
padding: 8px;
border: 1px solid black;
}
th {
background-color: #ddd;
}
td {
height: 80px;
}
.today {
background-color: yellow;
}
</style>
</head>
<body>
<h1>JavaScript 日历示例</h1>
<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>
<script>
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const today = date.getDate();
const daysInMonth = new Date(year, month, 0).getDate();
const firstDay = new Date(year, month - 1, 1).getDay();
const calendarBody = document.getElementById('calendar-body');
let dateCells = '';
let day = 1;
for (let i = 0; i < 6; i++) {
dateCells += '<tr>';
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
dateCells += '<td></td>';
} else if (day > daysInMonth) {
break;
} else {
if (day === today) {
dateCells += '<td class="today">' + day + '</td>';
} else {
dateCells += '<td>' + day + '</td>';
}
day++;
}
}
dateCells += '</tr>';
if (day > daysInMonth) {
break;
}
}
calendarBody.innerHTML = dateCells;
</script>
</body>
</html>
```
这个示例会生成当前月份的日历,可以根据需要进行修改。