Laravel实现特定时间自动高亮表格行(无需刷新页面)
实现服药时间自动高亮表格行的方案
1. 定义高亮样式
先添加CSS样式,让目标行有明显的视觉提示:
.highlight-row { background-color: #fff3cd; /* 浅黄色高亮 */ font-weight: bold; }
如果需要渐隐效果,可补充动画:
.highlight-row { background-color: #fff3cd; font-weight: bold; animation: fadeHighlight 30s forwards; } @keyframes fadeHighlight { to { background-color: transparent; font-weight: normal; } }
2. 渲染表格时携带服药时间数据
在Laravel Blade模板中,给每行添加data-med-time属性,存储格式化后的服药时间(统一为HH:mm格式),同时保留唯一标识:
<table> <thead> <tr> <th>ID</th> <th>名字</th> <th>姓氏</th> <th>服药时间</th> </tr> </thead> <tbody> @foreach($children as $child) <tr id="child-{{ $child->id_child }}" data-med-time="{{ \Carbon\Carbon::parse($child->time_to_take_medicine)->format('H:i') }}" > <td>{{ $child->id_child }}</td> <td>{{ $child->first_name }}</td> <td>{{ $child->last_name }}</td> <td>{{ $child->time_to_take_medicine }}</td> </tr> @endforeach </tbody> </table>
这里用Carbon处理时间格式化,确保前端拿到统一的时分格式。
3. 编写前端定时检查逻辑
用JavaScript实现每秒检查一次当前时间,匹配服药时间的行自动高亮30秒,同时避免重复触发:
// 存储已处理的高亮行ID,防止同一时间重复触发 const processedIds = new Set(); function checkMedicineSchedule() { // 获取当前时间的HH:mm格式 const now = new Date(); const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`; // 遍历所有儿童行 document.querySelectorAll('tbody tr').forEach(row => { const medTime = row.dataset.medTime; const childId = row.id.split('-')[1]; // 时间匹配且未处理过 if (medTime === currentTime && !processedIds.has(childId)) { row.classList.add('highlight-row'); processedIds.add(childId); // 30秒后移除高亮并清除记录 setTimeout(() => { row.classList.remove('highlight-row'); processedIds.delete(childId); }, 30000); } }); } // 每秒执行一次检查 setInterval(checkMedicineSchedule, 1000); // 页面加载时先执行一次初始化检查 checkMedicineSchedule();
注意事项
- 若数据库中
time_to_take_medicine是datetime类型,必须在Blade中提取纯时间部分,保证和前端当前时间格式一致。 - 时区问题:如果服务器与前端时区不同,需统一时区(比如都转换为UTC或本地时区),避免时间匹配错误。
内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

