FullCalendar v5如何限制仅在availableForMeeting时段内创建/选择事件
解决方案
你要的功能FullCalendar v5原生支持,无需复杂自定义逻辑,只需要修改2处核心配置即可实现和营业时间限制完全一致的效果:
- 核心改动1:将日历配置中的
selectConstraint和eventConstraint属性值从"businessHours"替换为"availableForMeeting"
FullCalendar的约束属性原生支持传入事件的groupId,配置后会自动限制用户的框选操作、已有事件的拖拽/调整大小操作,都只能在对应groupId覆盖的时段内执行,完全匹配你要的“绿色区域外无法选择创建事件”的需求。 - 核心改动2:保持你现有
select回调中对过去时间的判断、以及新建事件自动绑定constraint: 'availableForMeeting'的逻辑即可,这部分可以保证新建事件后续调整时也不会超出可用时段。
修改后的完整代码
<div id='calendar'></div> <div> Locales: <select id='locale-selector'></select> </div> <script> document.addEventListener('DOMContentLoaded', function () { var initialLocaleCode = 'en'; var localeSelectorEl = document.getElementById('locale-selector'); var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'timeGridWeek', selectable: true, unselectAuto: true, nowIndicator: true, editable: true, locale: initialLocaleCode, // 这里将约束改为自定义的可用时段groupId selectConstraint: "availableForMeeting", eventConstraint: "availableForMeeting", headerToolbar: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, events: [ { "title": "Meeting", "start": "2021-10-21T13:00:00", "end": "2021-10-21T13:40:00", "constraint": "availableForMeeting", "overlap": false, "color": "#257e4a" }, { "groupId": "availableForMeeting", "start": "2021-10-18T10:00:00", "end": "2021-10-18T17:00:00", "display": "background" }, { "groupId": "availableForMeeting", "start": "2021-10-21T12:00:00", "end": "2021-10-21T15:00:00", "display": "background" } ], select: function (selectionInfo) { var selectionStart = moment(selectionInfo.start); var today = moment(); // 无参数的moment默认取当前时间 if (selectionStart < today) { calendar.unselect() } else { var eventName = prompt('请输入事件标题'); if (eventName) { var newEvent = { title: eventName, start: selectionInfo.start, end: selectionInfo.end, allDay: false, stick: true, constraint: 'availableForMeeting' }; calendar.addEvent(newEvent); } } }, selectOverlap: function (event) { return event.rendering === 'background'; } }); calendar.setOption('businessHours', [ { daysOfWeek: [1, 2, 3, 4, 5], startTime: '08:00', endTime: '12:00' }, { daysOfWeek: [1, 2, 3, 4, 5], startTime: '13:00', endTime: '17:00' } ] ); calendar.render(); // 构建语言选择器选项 calendar.getAvailableLocaleCodes().forEach(function (localeCode) { var optionEl = document.createElement('option'); optionEl.value = localeCode; optionEl.selected = localeCode == initialLocaleCode; optionEl.innerText = localeCode; localeSelectorEl.appendChild(optionEl); }); // 监听语言选择器变更,动态修改日历配置 localeSelectorEl.addEventListener('change', function () { if (this.value) { calendar.setOption('locale', this.value); } }); }); </script>
补充说明
如果你需要同时保留营业时间的限制,只需要保证availableForMeeting对应的背景事件的时段都设置在你定义的营业时间范围内即可,无需额外添加校验逻辑。
内容的提问来源于stack exchange,提问作者Dhiraj
相关产品推荐
相关产品推荐

