FullCalendar资源营业时间外日期置灰及事件拖拽限制问题求助
解决方案:给指定资源的非营业时间置灰并禁止拖拽
要实现Resource A的businessHours(2024-01-19至2024-01-30)之外日期背景置灰,同时禁止事件拖拽到该范围外,需要通过FullCalendar的自定义样式钩子和拖拽权限控制来实现,以下是修改后的完整代码:
document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); // 提前定义Resource A的营业时间范围,方便后续复用 const resourceABusinessHours = { start: new Date('2024-01-19'), end: new Date('2024-01-30') }; var calendar = new FullCalendar.Calendar(calendarEl, { timeZone: 'UTC', initialView: 'resourceTimelineDay', aspectRatio: 1.5, headerToolbar: { left: 'prev,next', center: 'title', right: 'resourceTimelineDay,resourceTimelineWeek,resourceTimelineMonth' }, editable: true, resourceAreaHeaderContent: 'Rooms', resources: [ { "id": "a", "title": "Auditorium A", businessHours: resourceABusinessHours }, { "id": "b", "title": "Auditorium B", "eventColor": "green" }, { "id": "c", "title": "Auditorium C", "eventColor": "orange" } ], events: [ { "resourceId": "b", "title": "event 5", "start": "2024-01-19T10:00:00+00:00", "end": "2024-01-19T15:00:00+00:00" }, { "resourceId": "a", "title": "event 2", "start": "2024-01-19T09:00:00+00:00", "end": "2024-01-19T14:00:00+00:00" } ], // 给Resource A的非营业时间槽位添加灰化样式 slotClassNames: function({ resource, date }) { if (resource.id === 'a') { const slotDate = new Date(date.toISOString().split('T')[0]); // 提取日期部分(忽略时间) // 判断当前日期是否在营业时间之外 if (slotDate < resourceABusinessHours.start || slotDate >= resourceABusinessHours.end) { return 'non-business-hour'; // 返回自定义类名 } } return ''; }, // 禁止拖拽/调整事件到Resource A的非营业时间 eventAllow: function(dropInfo, draggedEvent) { if (draggedEvent.resourceId === 'a') { const eventStart = new Date(dropInfo.start.toISOString().split('T')[0]); const eventEnd = new Date(dropInfo.end.toISOString().split('T')[0]); // 检查事件的开始/结束日期是否超出营业时间范围 if (eventStart < resourceABusinessHours.start || eventEnd >= resourceABusinessHours.end) { return false; // 禁止操作 } } return true; // 其他资源允许正常操作 }, // 禁止在Resource A的非营业时间创建新事件 selectAllow: function(selectInfo) { if (selectInfo.resource.id === 'a') { const selectStart = new Date(selectInfo.start.toISOString().split('T')[0]); const selectEnd = new Date(selectInfo.end.toISOString().split('T')[0]); if (selectStart < resourceABusinessHours.start || selectEnd >= resourceABusinessHours.end) { return false; } } return true; } }); calendar.render(); });
添加CSS样式实现灰化效果:
.non-business-hour { background-color: #f0f0f0; /* 浅灰色背景 */ opacity: 0.7; }
关键说明:
- slotClassNames:针对每个时间槽位判断所属资源,若为Resource A且日期不在营业时间内,添加自定义CSS类实现背景灰化,这里提取日期部分(忽略时间)确保整日期槽位都被处理。
- eventAllow:控制事件拖拽/调整权限,当拖拽事件属于Resource A时,检查目标日期是否在营业时间内,不在则禁止操作。
- selectAllow:额外限制在Resource A的非营业时间无法创建新事件,完善交互逻辑。
内容的提问来源于stack exchange,提问作者Aman Gojariya
相关产品推荐
相关产品推荐

