PHP日历年份切换功能实现求助:添加年份切换按钮
没问题,我来帮你搞定这个年份切换的功能!核心思路是通过URL参数传递要显示的年份,动态生成对应年份的日历,同时添加上下年份的切换按钮。我给你修改好完整的代码,再一步步解释改动点~
修改后的完整代码
<?php // 处理年份参数:优先取URL传递的year值,默认显示2018年 $currentYear = isset($_GET['year']) && is_numeric($_GET['year']) ? (int)$_GET['year'] : 2018; // 限制年份范围(可选,避免极端年份导致异常) $currentYear = max(1900, min(2100, $currentYear)); $prevYear = $currentYear - 1; $nextYear = $currentYear + 1; // 月份数组 $months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; ?> <!DOCTYPE html> <html> <head> <title><?php echo $currentYear; ?>年日历</title> <style> .calendar-wrapper { display: flex; } .sidebar { padding: 15px; border: 1px solid #eee; margin-right: 25px; min-width: 120px; } .sidebar button { width: 100%; padding: 10px; margin: 8px 0; cursor: pointer; border: none; background: #f0f0f0; border-radius: 4px; } .sidebar button:hover { background: #e0e0e0; } .sidebar h2 { margin: 10px 0; text-align: center; } .calendar-container { display: flex; flex-wrap: wrap; gap: 15px; } .month-card { padding: 10px; border: 1px solid #ccc; border-radius: 6px; width: 200px; } .weekdays { display: flex; justify-content: space-around; font-weight: bold; margin-bottom: 8px; } .days-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; } .day-cell { text-align: center; padding: 5px; } .empty-cell { visibility: hidden; } </style> </head> <body> <div class="calendar-wrapper"> <!-- 侧边年份切换按钮 --> <div class="sidebar"> <button onclick="window.location.href='?year=<?php echo $prevYear; ?>'">← 上一年</button> <h2><?php echo $currentYear; ?>年</h2> <button onclick="window.location.href='?year=<?php echo $nextYear; ?>'">下一年 →</button> </div> <!-- 日历主体 --> <div class="calendar-container"> <?php foreach ($months as $index => $month): ?> <?php $monthNum = $index + 1; ?> <div class="month-card"> <h3><?php echo $month; ?></h3> <div class="weekdays"> <span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span> </div> <div class="days-grid"> <?php // 获取当月第一天的星期数(0=周日,1=周一...6=周六) $firstDayOfWeek = date('w', strtotime("$currentYear-$monthNum-01")); // 获取当月总天数 $totalDays = cal_days_in_month(CAL_GREGORIAN, $monthNum, $currentYear); // 填充月初的空白格子 for ($i = 0; $i < $firstDayOfWeek; $i++) { echo '<div class="day-cell empty-cell"></div>'; } // 填充当月日期 for ($day = 1; $day <= $totalDays; $day++) { echo "<div class='day-cell'>$day</div>"; } ?> </div> </div> <?php endforeach; ?> </div> </div> </body> </html>
关键改动说明
动态年份处理
- 用
$_GET['year']获取URL传递的年份参数,判断参数是否为合法数字,合法则使用该年份,否则默认显示2018年 - 加了可选的年份范围限制(1900-2100),避免输入极端年份导致日历生成异常
- 用
侧边切换按钮
- 在页面左侧添加了侧边栏,包含「上一年」「当前年份标题」「下一年」三个元素
- 按钮通过
onclick事件跳转到带对应年份参数的当前页面,也可以替换成<a>标签(比如<a href="?year=<?php echo $prevYear; ?>">← 上一年</a>),效果一致
日历适配动态年份
- 把原代码中固定的
2018替换成$currentYear变量,确保生成的是对应年份的日历(比如计算当月第一天、当月总天数的逻辑都用动态年份)
- 把原代码中固定的
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

