简体   繁体   中英

javascript Change background Based on Time

Ok, so I have been working with javascript for a little bit and Im trying to get it so that the website background changes depending on the time, Day and Night. But It seems that when I run the page that it skips over all the coding, goes to the else statement and run's that

Here Is the code:

</body>
<script type="text/javascript">
    var currentTime = new Date().getHours();
    if(5 < currentTime && currentTime < 18){
        if (document.body) {
            document.body.background = 'images/bg-day.png';
        }
    } else {
        if (document.body) {
            document.body.background = 'images/bg-night.png';
        }
    }
</script>
</html>

put all the js codes in

window.onload=function(){
    YOUR CODE HERE
}

to run them

and also,use
document.body.setAttribute("style","background-image: url(/images/xxx.png);") ;

instead of

document.body.background=xxx;  

because when you change css style,browser will refresh element immediately.

Your exact code works correctly for me. Try doing: document.write(currentTime);

To see if getHours(), etc is working as expected.

Also, what happens if you set currentTime manually?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM