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

如何在FullCalendar时间线视图中按条件修改事件颜色

需求:FullCalendar时间线视图按条件设置事件颜色

我正在开发一个项目,需要用FullCalendar的时间线视图展示数据,通过PHP和MySQL从数据库获取数据。目前的代码如下,希望实现按条件(比如status为Found/Not Found)给事件设置不同颜色的效果。

当前JS代码

document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');

var calendar = new FullCalendar.Calendar(calendarEl, {
  timeZone: 'UTC',
  aspectRatio: 1.5,
  scrollTime: '00:00',

  headerToolbar: {
    left: 'prev,next',
        center: 'title',
        right: 'resourceTimelineDay,resourceTimelineThreeDays,resourceTimelineWeek,resourceTimelineMonth'
  },
  initialView: 'resourceTimelineDay',
  
  views: {
    resourceTimelineThreeDays: {
      type: 'resourceTimeline',
      duration: { days: 3 },
      buttonText: '3 days'
    }
  },
  resourceAreaWidth: '15%',
  resourceAreaHeaderContent: 'Components',

  resources:  
  [
    
    { id: '1', title: 'Company', eventColor: 'orange' },
    { id: '3', title: 'Driver', eventColor: 'purple' },
    { id: '4', title: 'Summon', eventColor: 'red' },
    { id: '5', title: 'Summon Tracking', eventColor: 'green' }
  ],
  
  events: 
  [
    
   <?php  echo implode(",",$company); ?>,
   <?php  echo implode(",",$driver); ?>,
   <?php  echo implode(",",$summon); ?>,
   <?php  echo implode(",",$tracking); ?>
    
    ]
});

calendar.render();
});

当前PHP代码(处理Summon Tracking事件)

// Summon Tracking
$sql = $connection->prepare("SELECT * FROM saman 
WHERE vehicle_no = '".$_POST['vehicle']."'");
$sql->execute();

$result_track = $sql->get_result();
$i = 1;

$count_track = $result_track->num_rows;
if($count_track > 0){

while($row = $result_track->fetch_assoc())
{
  $sqlfound = "SELECT status, driver_name from saman WHERE status='Found'";
  $sqlnotfound = "SELECT status, driver_name from saman WHERE status='Not Found'";

  if($result = mysqli_query($connection, $sqlfound)){

$tracking[] = " { id: '".$i."', 
    resourceId: '5', 
    description: 'description for All Day Event',
    start: '".$row['datetime']."', 
    end: '".$row['datetime']."', 
    title: '".$row['status']."' }";

    $i++;
}else if($result = mysqli_query($connection, $sqlnotfound)){
  $tracking[] = " { id: '".$i."', 
    resourceId: '5', 
    start: '".$row['datetime']."', 
    end: '".$row['datetime']."', 
    title: '".$row['status']."' }";


    $i++;
}
}
}else 
{
    $tracking[] = " { id: '', 
        resourceId: '5', 
        start: '', 
        end: '',   
        title: '' }";
}


$sql->close();

解决方案:按条件设置事件颜色

1. 修复PHP逻辑,直接根据当前行的status设置颜色

原PHP代码重复查询全表status属于冗余操作,直接用当前行的$row['status']判断即可,同时给事件添加backgroundColor和borderColor属性来指定颜色:

// Summon Tracking
// 修复SQL注入风险:使用预处理语句绑定参数
$sql = $connection->prepare("SELECT * FROM saman WHERE vehicle_no = ?");
$sql->bind_param("s", $_POST['vehicle']);
$sql->execute();

$result_track = $sql->get_result();
$i = 1;
$tracking = [];

$count_track = $result_track->num_rows;
if($count_track > 0){
    while($row = $result_track->fetch_assoc())
    {
        $eventColor = '';
        // 根据status匹配对应颜色
        if($row['status'] === 'Found'){
            $eventColor = 'green';
        }else if($row['status'] === 'Not Found'){
            $eventColor = 'red';
        }

        $tracking[] = " { 
            id: '".$i."', 
            resourceId: '5', 
            description: 'description for All Day Event',
            start: '".$row['datetime']."', 
            end: '".$row['datetime']."', 
            title: '".$row['status']."',
            backgroundColor: '".$eventColor."',
            borderColor: '".$eventColor."'
        }";
        $i++;
    }
}else {
    // 无数据时不要添加空事件,避免视图出现无效条目
}

$sql->close();

2. 可选:用FullCalendar的JS回调动态设置颜色

如果不想在PHP层处理,也可以在JS中通过eventDidMount回调,根据事件的标题或自定义字段动态修改样式:

document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');

var calendar = new FullCalendar.Calendar(calendarEl, {
  // 保留原有配置...
  
  events: [
    <?php echo implode(",",$company); ?>,
    <?php echo implode(",",$driver); ?>,
    <?php echo implode(",",$summon); ?>,
    <?php echo implode(",",$tracking); ?>
  ],
  
  // 添加事件渲染完成后的回调
  eventDidMount: function(info) {
    if(info.event.title === 'Found'){
      info.el.style.backgroundColor = 'green';
      info.el.style.borderColor = 'green';
    }else if(info.event.title === 'Not Found'){
      info.el.style.backgroundColor = 'red';
      info.el.style.borderColor = 'red';
    }
  }
});

calendar.render();
});

关键注意点

  • 原PHP代码存在SQL注入风险,必须使用预处理语句绑定参数,修复后的代码已处理该问题。
  • 避免添加空事件,否则会导致FullCalendar渲染无效条目,影响视图体验。
  • FullCalendar支持backgroundColor(背景色)、borderColor(边框色)、textColor(文字色)等颜色属性,可按需调整。

内容的提问来源于stack exchange,提问作者Yamin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:00:52