javascript - 我尝试使用当前时间更改背景颜色

标签 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: Cannot read property 'style' of null at design.js:3”

最佳答案

这应该可以,但可能在错误的地方被调用,它应该在页面加载后调用,我建议将它放在正文末尾的标记中,或者您可以使用按钮并将其放置在函数中

关于javascript - 我尝试使用当前时间更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094340/

相关文章:

javascript - 如何在元素的类属性中使用javascript函数

javascript - 了解 .map 和 Stringify 与对象

php - 如何将请求重定向到 apache 服务器上的 'www' 子域

http - URL中的参数分隔符,误用问号的情况

android - Android 的两种颜色背景

javascript - 根据内部宽度显示脚本 - 不带 "potentially dangerous request.form"

python - 有人知道任何用户信誉引擎吗?

ios - UIButton 背景图像调整大小

html - 背景图片左边距问题

javascript - 将 Google map API 与 Meteor.js 结合使用