以下是一个示例,展示了如何创建一个基本的日历
日历
1. HTML 结构
首先,创建一个基本的 HTML 结构,用于展示日历。
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>日历</title><link rel="stylesheet" href="styles.css">
</head>
<body><div class="calendar"><div class="header"><button id="prev">上一月</button><h2 id="monthYear"></h2><button id="next">下一月</button></div><div class="days"><div class="day">日</div><div class="day">一</div><div class="day">二</div><div class="day">三</div><div class="day">四</div><div class="day">五</div><div class="day">六</div></div><div id="dateGrid" class="date-grid"></div></div><script src="script.js"></script>
</body>
</html>
2. CSS 样式
接下来,使用 CSS 来美化日历。
/* styles.css */
body {font-family: Arial, sans-serif;background-color: #f4f4f4;display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;
}.calendar {background: white;border-radius: 10px;box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);overflow: hidden;
}.header {display: flex;justify-content: space-between;align-items: center;padding: 10px 20px;background: #007bff;color: white;
}.days {display: grid;grid-template-columns: repeat(7, 1fr);background: #f0f0f0;
}.day {padding: 10px;text-align: center;font-weight: bold;
}.date-grid {display: grid;grid-template-columns: repeat(7, 1fr);
}.date {padding: 20px;text-align: center;cursor: pointer;
}.date:hover {background: #007bff;color: white;border-radius: 5px;
}
3. JavaScript 功能
最后,使用 JavaScript 来实现日历的动态功能。
// script.js
const monthYearElement = document.getElementById('monthYear');
const dateGridElement = document.getElementById('dateGrid');
const prevButton = document.getElementById('prev');
const nextButton = document.getElementById('next');let currentDate = new Date();function renderCalendar(date) {dateGridElement.innerHTML = '';const year = date.getFullYear();const month = date.getMonth();monthYearElement.innerText = date.toLocaleString('default', { month: 'long', year: 'numeric' });const firstDay = new Date(year, month, 1);const lastDay = new Date(year, month + 1, 0);const daysInMonth = lastDay.getDate();const startDay = firstDay.getDay();for (let i = 0; i < startDay; i++) {const emptyDiv = document.createElement('div');dateGridElement.appendChild(emptyDiv);}for (let day = 1; day <= daysInMonth; day++) {const dateDiv = document.createElement('div');dateDiv.classList.add('date');dateDiv.innerText = day;dateGridElement.appendChild(dateDiv);}
}prevButton.addEventListener('click', () => {currentDate.setMonth(currentDate.getMonth() - 1);renderCalendar(currentDate);
});nextButton.addEventListener('click', () => {currentDate.setMonth(currentDate.getMonth() + 1);renderCalendar(currentDate);
});// 初始渲染
renderCalendar(currentDate);