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

如何根据办公日程修改FullCalendar非事件网格单元格背景色

解决方案

FullCalendar 没有直接提供非事件单元格的渲染钩子,但可以通过单元格挂载完成后的回调函数结合事件检查来实现需求,以下是针对时间网格视图的具体实现步骤:

核心思路

  1. 利用 timeGridCellDidMount 钩子(时间网格视图专用),在每个时间单元格渲染完成后触发处理逻辑
  2. 判断当前单元格是否处于办公日程内(周一至周五9:00-17:00)
  3. 检查该单元格是否包含事件,仅对无事件的单元格设置背景色

代码实现

document.addEventListener('DOMContentLoaded', function() {
  const calendarEl = document.getElementById('calendar');
  const calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: 'timeGridWeek',
    events: [/* 替换为你的办公预约事件数据 */],
    // 时间网格单元格挂载完成后触发
    timeGridCellDidMount: function(info) {
      const cellDate = info.date;
      const dayOfWeek = cellDate.getDay(); // 0=周日, 1-6=周一至周六
      const hour = cellDate.getHours();

      // 判断是否在办公时间范围内
      const isInOfficeHours = dayOfWeek >= 1 && dayOfWeek <= 5 && hour >= 9 && hour < 17;

      // 获取当前单元格的时间范围(适配不同的slotDuration)
      const cellStart = cellDate;
      const cellEnd = new Date(cellStart.getTime() + calendar.view.timeGridSettings.slotDuration);

      // 筛选出与当前单元格时间重叠的事件
      const eventsInCell = calendar.getEvents().filter(event => {
        return event.start < cellEnd && event.end > cellStart;
      });

      // 仅对无事件的单元格设置背景色
      if (eventsInCell.length === 0) {
        info.el.style.backgroundColor = isInOfficeHours ? '#e8f4f8' : '#f5f5f5';
      }
    }
  });

  calendar.render();
});

关键说明

  • slotDuration:自动适配日历的时间槽间隔(默认30分钟),确保事件重叠判断的准确性
  • 视图切换适配:当切换日/周视图时,timeGridCellDidMount 会重新触发,样式会自动更新
  • 月视图适配:如果需要针对月视图的天单元格处理,可替换为 dayCellDidMount 钩子,逻辑类似(判断当天是否为工作日、当天是否有事件)

内容的提问来源于stack exchange,提问作者marocano1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:33:23