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

FullCalendar v5(Angular环境):如何在12小时插槽周视图中修改当日背景色

如何在FullCalendar v5周视图(12小时插槽)中修改当前日期背景色

嘿,我刚好在Angular项目里用FullCalendar v5做过类似的需求,给你一步步拆解怎么实现——在12小时插槽的周视图里给当前日期改背景色其实很直观,主要靠日历的钩子和自定义CSS配合:

1. 先配置日历的基础参数

首先在你的Angular组件里,把日历设置为周视图(timeGridWeek),并将插槽时长设为12小时。同时可以指定插槽的时间范围,确保一天被分成两个12小时的块:

import { Component } from '@angular/core';
import { CalendarOptions } from '@fullcalendar/angular';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.css']
})
export class CalendarComponent {
  calendarOptions: CalendarOptions = {
    initialView: 'timeGridWeek', // 周视图
    slotDuration: '12:00:00', // 每个插槽12小时
    slotMinTime: '00:00:00', // 一天的起始时间
    slotMaxTime: '24:00:00', // 一天的结束时间
    timeZone: 'local', // 确保时区和本地一致,避免日期判断出错
    headerToolbar: {
      left: 'prev,next today',
      center: 'title',
      right: 'timeGridWeek,timeGridDay'
    },
    // 关键钩子:标记当前日期单元格
    dayCellDidMount: (info) => {
      // 把当前日期和单元格日期的时间部分清零,只比较日期
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const cellDate = new Date(info.date);
      cellDate.setHours(0, 0, 0, 0);

      // 如果是当天,给单元格加自定义类
      if (today.getTime() === cellDate.getTime()) {
        info.el.classList.add('current-day');
      }
    }
  };
}

2. 编写自定义CSS样式

接下来在组件的CSS文件里,针对我们添加的current-day类,给当天的所有12小时插槽设置背景色。这里要注意FullCalendar的DOM结构:每个日期单元格(.fc-day)下包含两个12小时的插槽(.fc-timegrid-slot),所以我们要选中这些子元素来应用样式:

/* 给当前日期的所有12小时插槽设置背景色 */
.current-day .fc-timegrid-slot {
  background-color: #e8f4fd; /* 替换成你想要的颜色 */
  opacity: 0.7; /* 可选:调整透明度,避免和日历原有样式冲突 */
}

/* 可选:给顶部的日期标题栏也加上背景色,增强辨识度 */
.current-day .fc-daygrid-day-top {
  background-color: #d1e7fd;
}

一些注意事项

  • 日期判断一定要清零时间部分:如果直接比较new Date()和单元格的info.date,会因为时间戳不同(比如当前是下午3点,单元格日期是凌晨0点)导致判断失败,所以必须把小时、分钟、秒、毫秒都设为0。
  • 时区问题:如果你的项目涉及多时区,记得在calendarOptions里设置正确的timeZone,比如'UTC'或者用户的时区,避免日期匹配错误。
  • 样式优先级:如果FullCalendar的默认样式覆盖了你的自定义样式,可以给CSS选择器加更高的优先级,比如加上组件的类名:.app-calendar .current-day .fc-timegrid-slot。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:32:36