一、介紹
FullCalendar 是一個功能強大、高度可定制的 JavaScript 日歷組件,用于在網頁中顯示和管理日歷事件。它支持多種視圖(月、周、日等),可以輕松集成各種框架,并提供豐富的事件處理功能。
二、實操
案例具體代碼如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>FullCalendar 日期選擇</title><!-- FullCalendar CSS --><link href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css" rel="stylesheet"><style>body {font-family: Arial, sans-serif;margin: 20px;}#calendar {max-width: 900px;margin: 0 auto;}.selection-info {margin-top: 20px;padding: 15px;background-color: #f0f8ff;border-radius: 5px;text-align: center;font-size: 18px;}.highlight {background-color: #ffeb3b;}</style>
</head>
<body><div id="calendar"></div><div class="selection-info"><p>您選擇的日期是: <strong><span id="selectedDate">請點擊日歷選擇</span></strong></p></div><!-- FullCalendar JS --><script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.js"></script><script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/locales/zh-cn.js"></script><script>document.addEventListener('DOMContentLoaded', function() {var calendarEl = document.getElementById('calendar');var selectedDateEl = document.getElementById('selectedDate');var currentSelectedDate = null;var calendar = new FullCalendar.Calendar(calendarEl, {initialView: 'dayGridMonth',locale: 'zh-cn',headerToolbar: {left: 'prev,next today',center: 'title',right: 'dayGridMonth,timeGridWeek,timeGridDay'},// 點擊日期時觸發dateClick: function(info) {// 移除之前的高亮if (currentSelectedDate) {var prevSelected = document.querySelector('.fc-day[data-date="' + currentSelectedDate + '"]');if (prevSelected) prevSelected.classList.remove('highlight');}// 添加新選擇的高亮info.dayEl.classList.add('highlight');// 更新選擇的日期currentSelectedDate = info.dateStr;selectedDateEl.textContent = formatChineseDate(info.date);// 你也可以在這里執行其他操作,如提交表單等// console.log('選擇的日期:', info.dateStr);},// 初始化后添加今天的高亮datesSet: function() {if (currentSelectedDate) {var selectedDay = document.querySelector('.fc-day[data-date="' + currentSelectedDate + '"]');if (selectedDay) selectedDay.classList.add('highlight');}}});calendar.render();// 格式化日期為中文顯示function formatChineseDate(date) {var year = date.getFullYear();var month = date.getMonth() + 1;var day = date.getDate();var weekdays = ['日', '一', '二', '三', '四', '五', '六'];var weekday = weekdays[date.getDay()];return year + '年' + month + '月' + day + '日 星期' + weekday;}});</script>
</body>
</html>
效果圖如下: