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

求助:JavaScript实现页面背景图随时间切换代码失效问题排查

修复section背景图随时间自动切换的代码问题

原代码存在的问题

  • 脚本位置错误:<script>标签写在了</html>标签外面,此时DOM还未完全加载,执行脚本时可能找不到#bg元素
  • 时间逻辑矛盾:所有条件都包含(hour*60 + mintues) > 570(即9:30之后),但第一个条件又限制hour <=9,导致只有9:31-9:59会触发第一个分支,完全不符合“早晨切换日出图”的需求
  • 变量名拼写错误:mintues应为minutes

修正后的代码

<!doctype html>
<html>
<body>
    <section id="bg" class="banner"></section>

    <script>
        // 计算当前时间的总分钟数
        const now = new Date(); 
        const hour = now.getHours(); 
        const minutes = now.getMinutes();
        const totalMinutes = hour * 60 + minutes;

        const bgElement = document.getElementById("bg");

        // 重新划分时间段:可根据需求调整时间节点
        if (totalMinutes >= 360 && totalMinutes < 540) {
            // 早晨6:00-9:00:日出图
            bgElement.style.backgroundImage = "url('../pics/background1.jpg')";
        } else if (totalMinutes >= 540 && totalMinutes < 1080) {
            // 白天9:00-18:00:日间图
            bgElement.style.backgroundImage = "url('../pics/background2.jpg')";
        } else if (totalMinutes >= 1080 && totalMinutes < 1200) {
            // 傍晚18:00-20:00:傍晚图
            bgElement.style.backgroundImage = "url('../pics/background3.jpg')";
        } else {
            // 夜晚20:00-次日6:00:夜间图
            bgElement.style.backgroundImage = "url('../pics/background4.jpg')";
        }
    </script>
</body>
</html>

额外说明

  • 把脚本放在<body>末尾,确保DOM元素加载完成后再执行脚本
  • 重新梳理了时间段逻辑,你可以根据实际需求调整时间节点(比如把早晨改成5:30-8:30,就把360改成330,540改成510)
  • 提前获取#bg元素,避免重复调用getElementById,提升代码效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:10:49