[英]having issue with background-image using JavaScript
I want integreat this JavaScript code to change the background-image depending on current time . 我希望此JavaScript代码能够根据当前时间更改背景图像。 the problem is nothing show up if i put the code in a simple html file.
如果我将代码放在简单的html文件中,问题就什么都没有显示出来。
The code is woking live here though: http://jsbin.com/femem/1/edit 该代码虽然在这里实时启动: http : //jsbin.com/femem/1/edit
here is the code: 这是代码:
HTML: 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>
code JavaScript: 代码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 + ")";
At the point when the script is run, the <body>
has not been reached yet and therefore document.body
is undefined (as the error you get in the console should tell you). 在运行脚本时,尚未到达
<body>
,因此未定义document.body
(因为在控制台中收到的错误应该告诉您)。
To fix this, simply move your script inside the <body>
- it can be right at the top if you want. 要解决此问题,只需将脚本移动到
<body>
-如果需要,它可以位于顶部。
Alternatively, with basic PHP: 或者,使用基本的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";
?>)">
This would avoid a "Flash of Unstyled Content" (FOUC) 这样可以避免出现“未样式化内容闪烁”(FOUC)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.