使用FullCalendar的gotoDate函数更新日历UI显示范围异常问题
解决FullCalendar gotoDate无法让已有范围内日期成为视图起始的问题
我明白你遇到的困扰了——当使用FullCalendar的gotoDate方法时,如果目标日期已经在当前视图的显示范围内,它只会确保日期可见,不会自动调整视图让这个日期成为显示范围的第一个日期。要实现你想要的效果,我们可以直接控制视图的起始日期,而不是依赖gotoDate的默认行为。
解决方案
修改你的updateDateRange函数,使用view.setDate方法来明确设置视图的起始日期,并指定视图的持续时长(对应你配置的14天周视图):
const updateDateRange = () => { const targetStartDate = new Date('10-04-2020'); // 直接设置视图起始日期为目标日期,同时保持14天的显示时长 calendar.view.setDate(targetStartDate, { duration: { days: 14 } }); };
原理说明
gotoDate的设计逻辑是确保目标日期可见:如果日期已经在当前视图范围内,它不会触发视图的重新定位;只有当日期不在当前视图时,才会跳转视图让其可见。view.setDate则是直接控制视图的起始位置,搭配你自定义的duration参数,可以精准让目标日期成为显示范围的第一个日期,无论它之前是否在视图内。
完整修改后的关键代码片段
const updateDateRange = () => { const targetStartDate = new Date('10-04-2020'); calendar.view.setDate(targetStartDate, { duration: { days: 14 } }); }; // 其余日历初始化代码保持不变 var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { events: [ { id: 'a', resourceId: 'a', title: 'All Day Event', start: '2020-09-01' }, { title: 'Long Event', start: '2020-09-07', end: '2020-09-10' }, ], allDaySlot: false, displayEventTime: false, header: false, plugins: ['dayGrid', 'timeGrid', 'rrule'], defaultView: 'timeGridWeek', resourceOrder: 'sort', defaultDate: new Date('10-01-2020'), schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', views: { month: { type: 'dayGridMonth' }, week: { type: 'resourceTimeline', slotLabelFormat: [{ weekday: 'short', day: 'numeric', month: 'short' }], resourceLabelText: 'Property', duration: { days: 14 }, dateIncrement: { days: 1 }, slotDuration: '24:00:00', }, }, themeSystem: 'bootstrap', eventOverlap: false, contentHeight: 'auto', resourceAreaWidth: '10%', resources: [{ id: 'a', title: 'Auditorium A' }], }); calendar.render();
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

