工作日日程表项目:将Moment.js代码转换为Day.js实现时段着色
工作日日程表:Moment.js转Day.js并修复时段着色问题
核心转换与修复要点
要把原Moment代码迁移到Day.js,只需替换关键API,同时修复时段着色的逻辑漏洞(这大概率是你着色功能失效的原因):
- 直接替换
moment()为dayjs():Day.js的API设计和Moment高度兼容,大部分调用无需修改 - 强制类型转换:从DOM属性获取的时段是字符串,必须转为数字后再和当前小时比较,否则字符串比较会出现逻辑错误(比如
"10" < "8"会被错误判定为true) - 先清除旧状态类:添加新颜色类前,移除
past/present/future类,避免样式叠加冲突
完整转换后的代码
var dateTime = $('#dateTime'); var saveBtn = document.querySelector(".saveBtn"); // Day.js获取当前小时 var currentHour = dayjs().hour(); function printDateTime() { // Day.js格式化日期,格式与Moment完全一致 var date = dayjs().format("dddd, MMM Do YYYY"); dateTime.text(date); } function hourTracker() { $('.timeSchedule').each(function () { // 提取时段ID并转为数字类型 var scheduleHour = Number($(this).attr("id").split("time")[1]); // 先清除所有状态类,避免样式冲突 $(this).removeClass("past present future"); if (scheduleHour < currentHour) { $(this).addClass("past"); } else if (scheduleHour === currentHour) { $(this).addClass("present"); } else { $(this).addClass("future"); } }); } $(".saveBtn").on("click", function () { var value = $(this).siblings(".description").val(); var time = $(this).parent().attr("id"); localStorage.setItem(time, value); }); // 优化:批量读取localStorage,减少冗余代码 $('.timeSchedule').each(function() { var timeId = $(this).attr("id"); $(this).find(".description").val(localStorage.getItem(timeId)); }); printDateTime(); hourTracker();
额外说明
- 确保已引入Day.js资源:
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/dayjs.min.js"></script> - 若需中文日期格式,额外引入中文locale并激活:
代码开头添加:<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/locale/zh-cn.js"></script>dayjs.locale('zh-cn');
内容的提问来源于stack exchange,提问作者AaronDreyer
相关产品推荐
相关产品推荐

