javascript改变背景基于时间 [英] javascript Change background Based on Time

查看:93
本文介绍了javascript改变背景基于时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我一直在使用javascript进行一些操作,Im试图获取它,以便网站背景根据时间,日夜而变化。但是,似乎当我运行跳过所有编码的页面时,转到else语句并运行它。



这里是代码:

 < / 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>


解决方案

将所有js代码放入

  window.onload = function(){
您的代码
}



运行它们



以及使用

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



而不是

  document.body.background = xxx; 

因为当您更改css风格时,浏览器会立即刷新元素。


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.

这篇关于javascript改变背景基于时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆