FullCalendar v5中scrollTime失效,需实现视图滚动至当前时间
解决FullCalendar v5 scrollTime不生效,滚动到当前时间线的问题
我看了你的代码,问题出在scrollTime配置在自定义resourceTimeGrid视图下可能没有被正确触发,或者我们可以换更可靠的方式来实现滚动到当前时间线的需求。下面给你两种可行的解决方案:
方案一:使用scrollToNow()方法手动滚动(最可靠)
FullCalendar v5提供了专门的scrollToNow()方法,可以直接让日历滚动到当前时间的位置,不需要依赖scrollTime配置。你只需要在日历渲染完成后调用这个方法即可:
var calendar = new FullCalendar.Calendar(calendarEl, { // 你的所有原有配置... eventClick: function (info) { $('.popover').popover('hide') $('a.popover-event' + info.event.id).popover('show') }, eventResize: function (info) { console.log(info); }, eventDidMount: function (event) { $(event.el).attr('data-trigger', 'focus') $(event.el).attr('tabindex', -1) }, timeZone: 'local', slotEventOverlap: false, eventColor: '#c1c1c1', editable: false, schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', initialView: 'resourceTimeGridTwoDay1', nowIndicator: true, initialDate: moment().format('YYYY-MM-DD'), slotMinTime: '08:00:00', slotMaxTime: '18:00:00', selectable: true, locales: 'ru', duration: { days: 1 }, scrollTime: moment().format("HH:mm:ss"), }); // 渲染日历后调用scrollToNow,直接定位到当前时间线 calendar.render(); calendar.scrollToNow();
这个方法会自动匹配nowIndicator的位置,不管你使用的是自定义视图还是内置视图,都能稳定生效。
方案二:修复scrollTime配置的问题
如果坚持想用scrollTime来实现,需要确保几个关键点:
- 替换moment格式化方式:FullCalendar v5内置了日期处理工具,直接用原生JS生成时间字符串更可靠,避免moment格式化可能带来的兼容性问题:
// 生成HH:mm:ss格式的当前时间字符串 scrollTime: new Date().toLocaleTimeString('en-US', {hour12: false, hour: '2-digit', minute:'2-digit', second:'2-digit'}) - 明确自定义视图的duration:在你的自定义视图配置里添加
duration,避免全局配置和视图默认配置冲突:views: { resourceTimeGridTwoDay1: { type: 'resourceTimeGrid', buttonText: '1 day', duration: { days: 1 } // 明确视图时长为1天 }, } - 检查时间范围有效性:当前时间必须落在
slotMinTime(08:00)和slotMaxTime(18:00)之间,否则scrollTime会自动定位到slotMinTime的位置。
额外小提示
你的editable设置为false,但依然保留了eventResize配置,这个不影响功能,但可以考虑注释或移除,让代码更整洁。
内容的提问来源于stack exchange,提问作者scrz
相关产品推荐
相关产品推荐

