以下是使用 JavaScript 制作简易日历的示例代码和相关解释:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易日历</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
border: 1px solid #ccc;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>简易日历</h1>
<div id="calendar"></div>
<script>
function generateCalendar(year, month) {
const calendarDiv = document.getElementById('calendar');
calendarDiv.innerHTML = '';
const date = new Date(year, month);
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
const daysInMonth = lastDay.getDate();
const startDay = firstDay.getDay() || 7;
let calendarHTML = '<table>';
calendarHTML += '<tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>';
calendarHTML += '<tr>';
for (let i = 1; i < startDay; i++) {
calendarHTML += '<td></td>';
}
for (let i = 1; i <= daysInMonth; i++) {
calendarHTML += `<td>${i}</td>`;
if ((i + startDay - 1) % 7 === 0) {
calendarHTML += '</tr><tr>';
}
}
calendarHTML += '</tr>';
calendarHTML += '</table>';
calendarDiv.innerHTML = calendarHTML;
}
// 示例:生成当前月份的日历
const today = new Date();
generateCalendar(today.getFullYear(), today.getMonth());
</script>
</body>
</html>
基础概念:
Date
对象:用于处理日期和时间。innerHTML
:用于获取或设置元素的 HTML 内容。优势:
应用场景:
这个简易日历通过获取指定的年份和月份,计算出该月的第一天是星期几以及这个月的总天数,然后动态生成表格形式的日历展示在页面上。如果要生成其他月份的日历,可以调用 generateCalendar
函数并传入相应的年份和月份参数。
领取专属 10元无门槛券
手把手带您无忧上云