【前端小实战】jQuery 实现万年历
以下是使用jQuery实现一个基本万年历的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 万年历</title>
<style>
.calendar { border: 1px solid #000; padding: 20px; max-width: 240px; margin: 20px auto; }
.calendar th { text-align: center; }
.calendar td { text-align: center; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="calendar">
<table>
<thead>
<tr>
<th colspan="7">
<button class="prev-month"><</button>
<span class="current-month"></span>
<button class="next-month">></button>
</th>
</tr>
<tr>
<th>日</th>
<th>一</th>
<th>二</th>
<th>三</th>
<th>四</th>
<th>五</th>
<th>六</th>
</tr>
</thead>
<tbody>
<!-- 日历日期动态生成 -->
</tbody>
</table>
</div>
<script>
$(document).ready(function() {
showCalendar(new Date());
$('.prev-month').on('click', function() {
showCalendar(new Date($('.current-month').text().split('-')[0], $('.current-month').text().split('-')[1] - 2, 1));
});
$('.next-month').on('click', function() {
showCalendar(new Date($('.current-month').text().split('-')[0], $('.current-month').text().split('-')[1], 2));
});
function showCalendar(date) {
var month = date.getMonth(); // 获取当前月份
var year = date.getFullYear(); // 获取当前年份
var firstDayOfMonth = new Date(year, month, 1); // 当月的第一天
var lastDayOfMonth = new Date(year, month + 1, 0); // 当月的最后一天
var startDay = firstDayOfMonth.getDay(); // 当月的第一天是周几
var daysInMonth = lastDayOfMonth.getDate(); // 当月的总天数
var dayOfWeek = ['日', '一', '二', '三', '四', '五', '六'];
$('.current-month').text(year + '-' + (month + 1));
var html = '';
// 生成空白日历
for (var i = 0; i < startDay; i++) {
html += '<td></td>';
}
// 生成当月日历
for (var i = 1; i <= daysInMonth; i++) {
html += '<td>' + i + '</td>';
if ((i + startDay) % 7 === 0) {
html += '</tr><tr>';
}
}
// 如果最后一行不足七天,填充空白
while ((i + startDay) % 7 !== 1) {
评论已关闭