Changing background based on time of day (using javascript)

前端 未结 3 1699
无人及你
无人及你 2020-11-29 10:44

Okay, I have two different background .jpgs that I want to used as the backgroud depending on what time of day it is. I want the sunny background from 7am to 8pm and the nig

相关标签:
3条回答
  • 2020-11-29 11:13

    I'd recommend something slightly different than neo - rather than setting the image only, have two CSS classes, one for day and one for night - both can be in the same stylesheet. You can set the body's class depending on the time of day. This will allow you to do more than just the background.

    document.body.className = "day";
    or
    document.body.className = "night";
    
    0 讨论(0)
  • 2020-11-29 11:18

    You don't need to use a new stylesheet for each image. You can change only the background image from javascript:

    <html>
    <head>
        <title></title>
    </head>
    <body>
    
    </body>
    <script type="text/javascript">
    var currentTime = new Date().getHours();
    if (document.body) {
        if (7 <= currentTime && currentTime < 20) {
            document.body.background = "http://itsnotch.com/tumblr/images/daytime_bg.jpg";
        }
        else {
            document.body.background = "http://itsnotch.com/tumblr/images/nighttime_bg.jpg";
        }
    }
    </script>
    </html>
    

    EDIT: updated to show the recommended location of the script inside the page. This has been tested and works in Firefox and Internet Explorer.

    0 讨论(0)
  • 2020-11-29 11:23

    I have two different background .jpgs that I want to used as the backgroud depending on what time of day it is.

    I've written a more complete solution to this that can not only swap out an image for a night or day version, but select from pools of many images corresponding to all times of day.

    It uses php for the sun data at your given coordinates and pure css to do the animations (no javascript).

    for a demo see here:
    http://shawnfromportland.com/circadianCssWithPhp/

    for the source check it out here:
    https://github.com/shawnfromportland/circadianCssWithPhp

    0 讨论(0)
提交回复
热议问题