在FullCalendar周视图中添加可预约空闲时段按钮
在FullCalendar周视图添加可预约时段按钮的实现方案
针对你想在周视图时段添加预约按钮的需求,不用复杂的JS注入,直接利用FullCalendar的视图钩子就能实现,以下是基于v5+版本的具体方案:
核心实现代码
document.addEventListener('DOMContentLoaded', function() { const calendarEl = document.getElementById('calendar'); const calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'timeGridWeek', headerToolbar: { left: 'prev,next today', center: 'title', right: 'timeGridWeek,timeGridDay' }, // 视图加载完成后添加按钮 viewDidMount: function(info) { if (info.view.type !== 'timeGridWeek') return; const timeCells = document.querySelectorAll('.fc-timegrid-slot'); timeCells.forEach(cell => { if (cell.querySelector('.book-btn')) return; const bookBtn = document.createElement('button'); bookBtn.className = 'book-btn'; bookBtn.textContent = '预约'; bookBtn.style.cssText = 'margin-left: 10px; padding: 2px 8px; font-size: 12px;'; // 获取当前时段的起始时间 const slotDate = info.view.calendar.getDateFromPoint({ x: cell.offsetLeft, y: cell.offsetTop }); bookBtn.dataset.startTime = slotDate.toISOString(); // 绑定预约事件 bookBtn.addEventListener('click', function(e) { e.stopPropagation(); // 阻止触发日历默认的创建事件 const startTime = new Date(this.dataset.startTime); // 这里替换成你的实际预约逻辑:比如弹窗确认、提交到后端等 console.log('预约时段:', startTime.toLocaleString()); alert(`已预约时段:${startTime.toLocaleString()}`); }); cell.appendChild(bookBtn); }); }, // 切换视图时清理按钮,避免残留 viewWillUnmount: function(info) { if (info.view.type !== 'timeGridWeek') return; document.querySelectorAll('.book-btn').forEach(btn => btn.remove()); } }); calendar.render(); });
样式优化(可选)
给按钮加些样式让它更美观:
.book-btn { background-color: #2196F3; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.2s; } .book-btn:hover { background-color: #1976D2; }
关键细节说明
- 针对v4及以下版本,把
viewDidMount换成viewRender,viewWillUnmount换成viewDestroy即可 - 必须调用
e.stopPropagation(),否则点击按钮会触发FullCalendar默认的点击创建事件 - 通过
getDateFromPoint可以精准获取时段的时间,方便后续预约接口传参 - 检查
cell.querySelector('.book-btn')是为了避免重复添加按钮
内容的提问来源于stack exchange,提问作者Orosz Tamás
相关产品推荐
相关产品推荐

