我尝试通过使用当前时间来更改背景的颜色

时间:2019-05-11 21:18:31

标签: javascript web background

我尝试运行我的代码,但是它不起作用

我已经尝试使用rgb(x,x,x)代码,#xxxx(不带引号)来使用“颜色”变量...

var thehours = new Date().getHours();
if (thehours >= 0 && thehours < 12) {
     document.body.style.backgroundColor = "white";
} else if (thehours >= 12 && thehours < 18) {
    document.body.style.backgroundColor = "grey";
} else if (thehours >= 18 && thehours < 24) {
    document.body.style.backgroundColor = "black";  
}

在控制台中,我收到此消息:“ Uncaught TypeError:在design.js:3处无法读取null的'style'属性”

3 个答案:

答案 0 :(得分:0)

您的脚本是否在您的<head>标记中?如果是这样,请尝试将defer添加到您的<script>标记中。

例如:

<script type="text/javascript" src="design.js" defer></script>

答案 1 :(得分:0)

您需要确保在运行脚本之前已定义document.body元素(例如,如果您在body中运行脚本,则不会定义<head> <html>文档的内容

确保定义document.body的一种方法是将脚本包装在DOMContentLoaded对象上的document事件处理程序中,如下所示:

/* Set up the DOMContentLoaded event handler on the document to ensure
your script is only run once the document.body is defined */
document.addEventListener('DOMContentLoaded', function() {

  /* This script only runs once the whole page's "load" event fires 
  which means that the body element will be defined */
  var thehours = new Date().getHours();
  if (thehours >= 0 && thehours < 12) {
    /* Modified for this demo */
    document.body.style.backgroundColor = "blue"; 
  } else if (thehours >= 12 && thehours < 18) {
    document.body.style.backgroundColor = "grey";
  } else if (thehours >= 18 && thehours < 24) {
    document.body.style.backgroundColor = "black";
  }    

});

有关DOMContentLoaded事件的更多信息,请参见this link

答案 2 :(得分:0)

这应该可以,但是可能在错误的位置被调用,应该在页面加载后调用,我建议您将其放在标签的末尾,或者可以使用按钮并将其放置在功能中