You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:42:30