[英]having issue with background-image using JavaScript
我希望此JavaScript代码能够根据当前时间更改背景图像。 如果我将代码放在简单的html文件中,问题就什么都没有显示出来。
该代码虽然在这里实时启动: http : //jsbin.com/femem/1/edit
这是代码:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="js/bg.js"></script>
</head>
<body>
<h1>
some text
</h1>
</body>
</html>
代码JavaScript:
var d = new Date(),
h = d.getHours(),
i;
if (h < 6) {
i = "http://placehold.it/450x150";
} else if (h < 10) {
i = "http://placehold.it/250x150";
} else if (h < 18) {
i = "http://placehold.it/350x150";
} else if (h < 23) {
i = "bgbody.jpg";
} else {
i = "http://placehold.it/450x150";
}
document.body.style.background = "url(" + i + ")";
在运行脚本时,尚未到达<body>
,因此未定义document.body
(因为在控制台中收到的错误应该告诉您)。
要解决此问题,只需将脚本移动到<body>
-如果需要,它可以位于顶部。
或者,使用基本的PHP:
<body style="background-image:url(<?php
$h = date("H");
if( $h < 6) echo "http://placehold.it/450x150";
elseif( $h < 10) echo "http://placehold.it/250x150";
elseif( $h < 18) echo "http://placehold.it/350x150";
elseif( $h < 23) echo "bgbody.jpg";
else echo "http://placehold.it/450x150";
?>)">
这样可以避免出现“未样式化内容闪烁”(FOUC)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.