You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现FullCalendar月视图按起止时间显示对应长度的事件条形

解决方案

FullCalendar可以实现月视图中基于起止时间展示事件的需求,具体可通过以下配置和自定义方式实现:

1. 基础配置调整

首先在初始化配置中开启事件时间显示,强制所有事件以条形块显示,替代默认的短事件圆点样式:

document.addEventListener('DOMContentLoaded', function() {
  const calendarEl = document.getElementById('calendar');
  const calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: 'dayGridMonth',
    events: [
      // 示例事件:需包含具体时分秒
      {
        title: '10-14点会议',
        start: '2024-05-20T10:00:00',
        end: '2024-05-20T14:00:00'
      }
    ],
    displayEventTime: true, // 显示事件起止时间
    eventDisplay: 'block', // 强制所有事件以条形块展示
    dayMaxEventRows: true // 处理多事件堆叠问题
  });
  calendar.render();
});

2. 自定义匹配时长的事件条形

仅基础配置无法让条形完全匹配事件时长,可通过两种方式优化:

方式一:自定义事件渲染逻辑

通过eventContent回调函数,根据事件起止时间计算当天内的时长占比,动态设置事件高度:

eventContent: function(info) {
  // 计算事件在当天的时长占比
  const start = info.event.start;
  const end = info.event.end;
  const dayStart = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const dayDuration = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const eventDuration = end - start;
  const heightRatio = eventDuration / dayDuration;
  // 设置最小高度避免过短事件显示过窄
  const eventHeight = Math.max(heightRatio * 100, 20) + '%';

  return {
    html: `<div class="custom-event" style="height: ${eventHeight}">
            <span class="event-title">${info.event.title}</span>
            <span class="event-time">${info.timeText}</span>
          </div>`
  };
}

配合CSS美化样式:

.custom-event {
  background-color: #378006;
  border-radius: 3px;
  padding: 2px 4px;
  color: #fff;
  overflow: hidden;
}
.event-title {
  display: block;
  font-size: 0.8em;
}
.event-time {
  font-size: 0.7em;
  opacity: 0.8;
}

方式二:切换到timeGridMonth视图

若不需要严格的dayGridMonth布局,timeGridMonth视图自带时间轴,事件会自动匹配起止时间长度:

initialView: 'timeGridMonth',
slotDuration: '01:00:00', // 时间槽间隔设为1小时
slotMinTime: '08:00:00', // 单元格显示的起始时间
slotMaxTime: '18:00:00' // 单元格显示的结束时间

注意事项

  • 事件的start和end必须包含具体时分秒(如YYYY-MM-DDTHH:mm:ss格式),否则会被识别为全天事件。
  • 多事件堆叠时,可通过eventOrder配置调整事件排序优先级。

内容的提问来源于stack exchange,提问作者Farshad Bakhshandegan Moghadda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:44:56