使用JavaScript遇到背景图像问题

时间:2014-03-08 22:49:05

标签: 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 + ")";

1 个答案:

答案 0 :(得分:1)

在运行脚本时,尚未到达<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)