如何实现每日零点自动切换类的背景色而非依赖用户事件
实现每日零点自动切换背景色(不受页面刷新影响)
现有一段代码每24小时切换指定元素的背景色,但存在问题:用户刷新页面后,24小时周期会重新开始,必须保持页面不刷新满24小时才能看到颜色变化。需求改为每日零点自动切换背景色,不受任何用户操作或页面刷新影响。
当前代码:
<script> const bgColor = ["#DA6F33", "#33B2dA", "#66BD9E", "#667FBD"]; const backgroundSection = document.querySelector(".twofirst"); let i = 0; function changeColor() { backgroundSection.style.backgroundColor = bgColor[i]; i = (i + 1) % bgColor.length; }; setInterval(changeColor, 86400000); </script>
解决方案
核心思路是根据当前日期计算颜色索引,而非依赖页面运行时长,确保同一天显示同色,零点自动切换,刷新页面也不会打乱周期。
修改后的代码:
<script> const bgColor = ["#DA6F33", "#33B2dA", "#66BD9E", "#667FBD"]; const backgroundSection = document.querySelector(".twofirst"); // 计算对应当日的颜色索引 function getCurrentColorIndex() { // 设定一个固定起始日期(需早于当前日期) const startDate = new Date(2024, 0, 1); const today = new Date(); // 计算从起始日到今日的天数差 const daysDiff = Math.floor((today - startDate) / (1000 * 60 * 60 * 24)); // 取模实现颜色循环 return daysDiff % bgColor.length; } // 设置当日初始背景色 function setInitialColor() { const index = getCurrentColorIndex(); backgroundSection.style.backgroundColor = bgColor[index]; } // 调度次日零点的颜色切换 function scheduleNextChange() { const now = new Date(); // 计算次日零点时间 const nextMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); const timeToMidnight = nextMidnight - now; // 零点触发切换,并重新调度下一次 setTimeout(() => { setInitialColor(); scheduleNextChange(); }, timeToMidnight); } // 页面加载时立即执行 setInitialColor(); scheduleNextChange(); </script>
关键逻辑说明
getCurrentColorIndex():通过固定起始日与当日的天数差取模,确保同一天返回相同索引,跨天后自动切换下一个颜色。setInitialColor():页面加载时直接设置当日对应颜色,刷新页面也能保持当日配色一致。scheduleNextChange():计算当前到次日零点的时间差,设置定时器在零点触发切换,并重新调度下一天的任务,实现长期自动循环。
内容的提问来源于stack exchange,提问作者Soe123
相关产品推荐
相关产品推荐

