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

如何实现高亮当前时间20分钟内的公交发车时间?

解决公交发车时间高亮问题

原代码的问题分析

  • new Date.now() 语法错误:Date.now() 是静态方法,不需要加new,直接调用就能获取当前时间戳
  • PHP变量$stop_time是循环生成的,原JS直接拼接只会拿到循环最后一个时间值,无法对应每个<td>元素
  • 时间处理逻辑错误:你需要判断当前时间20分钟内的发车时间,但原代码只判断了发车时间早于当前,且未处理时间范围;仅用H:i格式创建Date对象时,需手动绑定当天日期才能正确转换为时间戳
  • 未针对每个<td>单独处理时间,循环里用同一个stop值判断所有元素,逻辑完全错误

修正方案

1. 修改PHP代码,为每个<td>添加时间数据属性

把发车时间存在<td>的data-time属性中,让JS能直接获取每个元素对应的发车时间:

<tr>
  <?php if(have_rows('departure_times')): while(have_rows('departure_times')): the_row();
  $stop_time = get_sub_field('time'); // 返回格式为"H:i" ?>
    <td class="time" data-time="<?= $stop_time ?>">
      <span><?= $stop_time; ?></span>
    </td>
  <?php endwhile; endif; ?>
</tr>

2. 编写CSS高亮样式(比直接修改style更易维护)

.time.highlight {
  background-color: green;
  color: white; /* 可选:添加文字对比色提升可读性 */
}

3. 修正JS逻辑,逐个处理发车时间

// 获取当前时间戳(毫秒)
const now = Date.now();
// 计算当前时间+20分钟的时间戳(20*60*1000 = 1200000毫秒)
const twentyMinutesLater = now + 20 * 60 * 1000;

// 获取所有时间单元格
const timeSlots = document.querySelectorAll('.time');

timeSlots.forEach(slot => {
  // 取出当前单元格的发车时间字符串
  const stopTimeStr = slot.dataset.time;
  // 将H:i格式拆分为时、分,转为当天的Date对象
  const [hours, minutes] = stopTimeStr.split(':');
  const stopDate = new Date();
  stopDate.setHours(hours, minutes, 0, 0); // 重置秒和毫秒,保证时间精度
  const stopTime = stopDate.getTime();

  // 判断发车时间是否在当前到未来20分钟范围内
  if (stopTime >= now && stopTime <= twentyMinutesLater) {
    slot.classList.add('highlight');
  }
});

补充说明

  • 如果需求是过去20分钟内已发车的时间,只需把判断条件改为:stopTime >= now - 20 * 60 * 1000 && stopTime <= now
  • 使用querySelectorAll比getElementsByClassName更灵活,返回静态NodeList,遍历更稳定
  • 用CSS类控制样式,后续修改高亮效果只需调整CSS,无需改动JS,符合前端开发规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:42:41