javascript - 使用 JavaScript 处理背景图片有问题

标签 javascript html css background-image

我想整合这段 JavaScript 代码以根据当前时间更改背景图像。 如果我将代码放在一个简单的 html 文件中,问题就没有出现。

虽然代码在这里生效:http://jsbin.com/femem/1/edit

代码如下:

HTML:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>

        <script src="js/bg.js"></script>

    </head>
    <body>
    <h1>
        some text
    </h1>
    </body>
    </html>

代码 JavaScript:

     var d = new Date(),
        h = d.getHours(),
        i;

    if (h < 6) {
        i = "http://placehold.it/450x150";
    } else if (h < 10) {
        i = "http://placehold.it/250x150";
    } else if (h < 18) {
        i = "http://placehold.it/350x150";
    } else if (h < 23) {
        i = "bgbody.jpg";
    } else {
        i = "http://placehold.it/450x150";
    }

    document.body.style.background = "url(" + i + ")";

最佳答案

在脚本运行时,<body>尚未达到,因此 document.body未定义(正如您在控制台中得到的错误应该告诉您的那样)。

要解决此问题,只需将您的脚本移到 <body> 中- 如果需要,它可以位于顶部。

或者,使用基本的 PHP:

<body style="background-image:url(<?php
    $h = date("H");
    if( $h < 6) echo "http://placehold.it/450x150";
    elseif( $h < 10) echo "http://placehold.it/250x150";
    elseif( $h < 18) echo "http://placehold.it/350x150";
    elseif( $h < 23) echo "bgbody.jpg";
    else echo "http://placehold.it/450x150";
?>)">

这将避免“无样式内容闪现”(FOUC)

关于javascript - 使用 JavaScript 处理背景图片有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22276070/

相关文章:

css - 如何通过滚动使溢出的 SVG 内容可见?

javascript - Material-UI 菜单问题

javascript - JS - PHP - 根据特定 HTML 标记的值构建数据数组

jquery - 通过单击指向 iframe 中的内部链接的链接向下滚动整个页面

html - ASP.Net 菜单在 IE 中表现异常

html - 为什么我的 CSS 样式会覆盖我的内联样式?

php - 更改 Wordpress 主题中的 "Load More"按钮的最佳方法是什么?

javascript - 设备锁定时停止播放 HTML5 音频(Android 和 iOS)

javascript - 在 jquery 插件模式中从公共(public)函数调用私有(private)函数

javascript - Admin Sdk 和实时数据库无法正常工作的 Firebase 功能