Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一天中不同时间的不同背景?_Javascript_Html_Css_Background - Fatal编程技术网

Javascript 一天中不同时间的不同背景?

Javascript 一天中不同时间的不同背景?,javascript,html,css,background,Javascript,Html,Css,Background,可能重复: 我想创建一个网站,在那里背景会在一天中的不同时间旋转一堆文件。是否有任何方法可以根据服务器或脚本时钟在特定时间绑定一点javascript来更改背景 我希望有一组白天/下午/晚上/晚上/晚上/黎明的背景,我想循环使用。使用中的代码,获取本地时间,并更改元素的CSS,以保持背景。您可以这样做,然后只需将i变量传递给元素背景图像: var d = new Date(), h = d.getHours(), i; if (h < 6) i = "night.jpg

可能重复:

我想创建一个网站,在那里背景会在一天中的不同时间旋转一堆文件。是否有任何方法可以根据服务器或脚本时钟在特定时间绑定一点javascript来更改背景


我希望有一组白天/下午/晚上/晚上/晚上/黎明的背景,我想循环使用。

使用中的代码,获取本地时间,并更改元素的CSS,以保持背景。

您可以这样做,然后只需将
i
变量传递给元素
背景图像

var d = new Date(),
    h = d.getHours(),
    i;

if (h < 6) i = "night.jpg";
else if (h < 9) i = "dawn.jpg";
else if (h < 15) i = "afternoon.jpg";
else if (h < 21) i = "day.jpg";
else i = "night.jpg";

document.body.style.background = "url("+i+")";
var d=new Date(),
h=d.getHours(),
我
if(h<6)i=“night.jpg”;
如果(h<9)i=“dawn.jpg”;
如果(h<15)i=“午后.jpg”;
如果(h<21)i=“day.jpg”;
else i=“night.jpg”;
document.body.style.background=“url(“+i+”);

将以下内容添加到HTML文档的开头:

<script type="text/javascript">
    (function(){
        var styles = ['night', 'dawn', 'afternoon', 'day', 'evening'];
        var currStyle = styles[Math.floor(styles.length * (new Date()).getHours() / 24)];
        document.documentElement.className += ' ' + currStyle;
    }());
</script>

其他人已经对此给出了一个答案。这不应该是class='url('+i+')?@Gerben是的,并且.style.background(using.body.background被弃用)不需要
h>=0
,因为Date.prototype.getHours将永远不会返回小于0的值。@RobG非常正确,在几次编辑之前有一个稍微不同的方法,没有理由就留在那里了。谢谢你指出这一点。
.night #myelement {
    background-image: url(myImage.jpg);
}
.day body {
    background-color: red;
}