Fullcalendar v5:如何在timeGridWeek视图中每行显示单个事件
实现FullCalendar v5 timeGridWeek视图事件垂直排列及高度自动扩展
1. 禁用事件重叠,实现垂直堆叠
设置eventOverlap: false,FullCalendar会自动将重叠事件垂直排列,而非并排显示。
2. 动态计算并调整时间网格高度
通过计算一周内同一时间段的最大事件堆叠数,动态调整时间网格的总高度,确保所有事件完整显示。
完整代码示例
document.addEventListener('DOMContentLoaded', function() { const calendarEl = document.getElementById('calendar'); const slotMinHeight = 40; // 单个插槽基础高度(可按需调整) const slotDuration = '00:30:00'; // 每个插槽的时间长度 const visibleHours = 9; // 一天显示的小时数(示例:9:00-18:00) const totalSlotsPerDay = (visibleHours * 60) / parseInt(slotDuration.split(':')[1]); const calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'timeGridWeek', eventOverlap: false, slotMinHeight: slotMinHeight, slotDuration: slotDuration, headerToolbar: { left: 'prev,next today', center: 'title', right: 'timeGridWeek,timeGridDay' }, events: [ // 示例事件数据 { title: '团队会议', start: '2024-05-20T09:00:00', end: '2024-05-20T10:00:00' }, { title: '客户沟通', start: '2024-05-20T09:30:00', end: '2024-05-20T10:30:00' }, { title: '代码评审', start: '2024-05-20T09:15:00', end: '2024-05-20T10:15:00' }, { title: '项目进度会', start: '2024-05-21T10:00:00', end: '2024-05-21T11:00:00' }, { title: '需求讨论', start: '2024-05-21T10:00:00', end: '2024-05-21T11:00:00' }, { title: '测试计划', start: '2024-05-21T10:00:00', end: '2024-05-21T11:00:00' } ], viewDidMount: (info) => adjustGridHeight(info.view), viewDidUpdate: (info) => adjustGridHeight(info.view) }); calendar.render(); function adjustGridHeight(view) { const eventElements = view.el.querySelectorAll('.fc-event'); let maxStackCount = 1; const stackCounts = {}; // 统计每个时间段的事件堆叠数量 eventElements.forEach(el => { const key = `${el.dataset.fcStart}-${el.dataset.fcEnd}`; stackCounts[key] = (stackCounts[key] || 0) + 1; maxStackCount = Math.max(maxStackCount, stackCounts[key]); }); // 计算并设置网格总高度 const totalHeight = slotMinHeight * totalSlotsPerDay * maxStackCount; view.el.querySelector('.fc-timegrid-body').style.height = `${totalHeight}px`; } });
3. 可选样式优化
添加自定义CSS确保事件内容完整显示:
.fc-event { min-height: 35px; }
内容的提问来源于stack exchange,提问作者Ali Mashal
相关产品推荐
相关产品推荐

