
本文详解如何在 fullcalendar 的周视图(agendaweek)中,基于日期+时间条件动态高亮单元格,替代简单 dom 操作,确保跨版本兼容性与响应式渲染。
在 FullCalendar 中,直接操作 .fc-day 类选择器(如月视图中 $('.fc-day[data-date="..."]'))在周视图(尤其是 agendaWeek 或 timeGridWeek)中不可靠——因为周视图的 DOM 结构以“时间轴行”(time slots)为核心,日期单元被拆分为多列小时/半小时区块,不存在统一的 data-date 属性容器。因此,必须借助官方提供的生命周期钩子进行精准控制。
✅ 推荐方案:使用 dayRender 钩子(v3)或 dayCellDidMount(v5+)
以下示例基于 FullCalendar v3(问题中代码风格匹配),若使用 v5/v6,请参考文末适配说明:
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
// 设置起止时间(支持 ISO 8601 字符串或 Moment 对象)
dayRender: function(date, cell) {
const startDate = moment('2023-04-02T09:00:00'); // 起始:4月2日 09:00
const endDate = moment('2023-04-06T17:30:00'); // 结束:4月6日 17:30
// 判断当前渲染的日期单元是否落在目标范围内(含时间精度)
if (date.isBetween(startDate, endDate, null, '[]')) {
$(cell).css('background-color', 'rgba(143, 223, 130, 0.5)');
// 可选:增强可访问性,添加 aria-label
$(cell).attr('aria-label', '高亮时段:' + date.format('YYYY-MM-DD HH:mm'));
}
}
});⚠️ 注意事项:dayRender 中的 date 参数是 当天 00:00:00 的 Moment 对象,仅含日期,不含具体时间点 —— 因此它适合按「整日」高亮;若需精确到小时/分钟(如仅高亮 14:00–16:00 区间),应改用 eventRender 或 slotLaneDidMount(v5+)配合自定义事件模拟。若需「时间维度高亮」(例如某天的 14:00–16:00 背景色),推荐创建透明占位事件(rendering: 'background'):events: [{ start: '2023-04-03T14:00:00', end: '2023-04-03T16:00:00', rendering: 'background', color: 'rgba(143,223,130,0.5)' }]
? FullCalendar v5/v6 适配提示
v5+ 已移除 fullCalendar() 方法,改用 @fullcalendar/interaction 等模块化包,且 dayRender 替换为 dayCellDidMount:
import { Calendar } from '@fullcalendar/core';
import timeGridPlugin from '@fullcalendar/timegrid';
const calendar = new Calendar(calendarEl, {
plugins: [timeGridPlugin],
initialView: 'timeGridWeek',
dayCellDidMount: function(info) {
const targetStart = new Date('2023-04-02T09:00:00');
const targetEnd = new Date('2023-04-06T17:30:00');
const cellDate = info.date; // Date 对象,精度为日
if (cellDate >= targetStart && cellDate <= targetEnd) {
info.el.style.backgroundColor = 'rgba(143, 223, 130, 0.5)';
}
}
});✅ 总结
- ✅ 优先使用 dayRender(v3)或 dayCellDidMount(v5+)实现按日高亮,语义清晰、性能稳定;
- ✅ 需要精确到时刻的背景高亮?请用 rendering: 'background' 类型事件,而非 DOM 操作;
- ❌ 避免在周视图中硬查 .fc-day[data-date] —— 该结构在 agendaWeek 中不存在,将导致静默失败;
- ? 所有时间比较务必使用标准时间对象(Moment 或原生 Date),避免字符串直比引发时区/格式错误。
通过以上方式,即可稳健、可维护地实现在 FullCalendar 周视图中按需高亮任意日期与时间范围。










