簡體   English   中英

使用JavaScript的背景圖片有問題

[英]having issue with background-image using JavaScript

我希望此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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM