简体   繁体   English

javascript根据时间更改背景

[英]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. 好的,所以我一直在使用javascript进行一些工作,而我正在尝试获取它,以便网站背景根据时间(白天和黑夜)而变化。 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 但是似乎当我运行该页面时,它会跳过所有编码,转到else语句并运行

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 将所有js代码放入

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

to run them 运行它们

and also,use 而且,使用
document.body.setAttribute("style","background-image: url(/images/xxx.png);") ; 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. 因为当您更改CSS样式时,浏览器会立即刷新元素。

Your exact code works correctly for me. 您的确切代码对我来说是正确的。 Try doing: document.write(currentTime); 尝试做:document.write(currentTime);

To see if getHours(), etc is working as expected. 查看getHours()等是否按预期工作。

Also, what happens if you set currentTime manually? 另外,如果手动设置currentTime会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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