resourceTimeGridWeek视图滚动后无时间信息,如何为单元格添加时间标识?
解决方案
针对resourceTimeGridWeek视图滚动右侧无时间信息的问题,提供两种实用方案:
方案一:为每个资源列的时间单元格添加时间标签
通过监听datesRender事件,在日历渲染完成后,将左侧的时间标签复制到每个资源列的对应时间单元格中,确保滚动时每个单元格都能显示时间。
代码实现
document.addEventListener('DOMContentLoaded', function() { const calendarEl = document.getElementById('calendar'); const calendar = new FullCalendar.Calendar(calendarEl, { schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', initialView: 'resourceTimeGridWeek', datesAboveResources: true, resources: [ // 替换为你的资源数据 { id: 'a', title: '资源A' }, { id: 'b', title: '资源B' }, // ... 其余资源 ], events: [ // 替换为你的事件数据 ], datesRender: function(info) { // 获取左侧原始时间标签 const timeLabels = info.el.querySelectorAll('.fc-timegrid-slot-label'); // 获取所有资源列(排除左侧时间轴列) const resourceCols = info.el.querySelectorAll('.fc-timegrid-body-col:not(.fc-timegrid-axis-col)'); resourceCols.forEach(col => { // 清除已存在的自定义标签,避免重复渲染 col.querySelectorAll('.custom-slot-label').forEach(el => el.remove()); // 遍历当前列的所有时间槽 const slots = col.querySelectorAll('.fc-timegrid-slot'); slots.forEach((slot, index) => { if (timeLabels[index]) { const labelText = timeLabels[index].textContent.trim(); const labelEl = document.createElement('div'); labelEl.className = 'custom-slot-label'; labelEl.textContent = labelText; // 设置标签样式,固定在单元格左上角 labelEl.style.position = 'absolute'; labelEl.style.top = '2px'; labelEl.style.left = '2px'; labelEl.style.fontSize = '0.8em'; labelEl.style.color = '#666'; slot.appendChild(labelEl); } }); }); } }); calendar.render(); });
配套CSS
确保时间槽单元格为相对定位,让自定义标签能正确定位:
.fc-timegrid-slot { position: relative; }
方案二:添加每日垂直分隔线及日期标识
通过CSS为每天的列添加右侧分隔线,并结合JS设置日期标识,让滚动时能清晰区分日期区间。
代码实现
1. 事件监听设置日期标识
document.addEventListener('DOMContentLoaded', function() { const calendarEl = document.getElementById('calendar'); const calendar = new FullCalendar.Calendar(calendarEl, { schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', initialView: 'resourceTimeGridWeek', datesAboveResources: true, resources: [/* 你的资源数据 */], events: [/* 你的事件数据 */], datesRender: function(info) { const dayCols = info.el.querySelectorAll('.fc-timegrid-body-col.fc-day'); dayCols.forEach(col => { const date = new Date(col.getAttribute('data-date')); // 格式化为友好的日期文本,如"周一 09/18" const formattedDate = date.toLocaleDateString('zh-CN', { weekday: 'short', month: '2-digit', day: '2-digit' }); col.setAttribute('data-date', formattedDate); }); } }); calendar.render(); });
2. 配套CSS添加分隔线和日期标签
/* 为每日列添加右侧分隔线 */ .fc-timegrid-body-col.fc-day { border-right: 1px solid #ddd; position: relative; } /* 在分隔线位置显示日期标识 */ .fc-timegrid-body-col.fc-day::after { content: attr(data-date); position: absolute; top: 0; right: -15px; transform: translateX(50%); font-size: 0.8em; color: #666; white-space: nowrap; }
注意事项
- 上述代码基于FullCalendar v5/v6版本,若使用旧版本,需根据实际DOM类名调整选择器。
- 可根据需求自定义时间标签的样式(如位置、颜色、字体大小),适配你的页面风格。
内容的提问来源于stack exchange,提问作者Harald Huemer
相关产品推荐
相关产品推荐

