質問

I want integreat this JavaScript code to change the background-image depending on current time . the problem is nothing show up if i put the code in a simple html file.

The code is woking live here though: http://jsbin.com/femem/1/edit

here is the code:

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>

code 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 + ")";
役に立ちましたか?

解決

At the point when the script is run, the <body> has not been reached yet and therefore document.body is undefined (as the error you get in the console should tell you).

To fix this, simply move your script inside the <body> - it can be right at the top if you want.

Alternatively, with basic 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";
?>)">

This would avoid a "Flash of Unstyled Content" (FOUC)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top