我想整合这段 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)
关于javascript - 使用 JavaScript 处理背景图片有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22276070/