javascript - 我试图用 JS 更改 CSS "body"属性的背景...我一直收到控制台错误 "newBgColor is not defined"

标签 javascript css function dom

我一直在尝试使用一个函数来更改 DOM 的背景颜色。我可能错过了一些 super “在我脸上”的东西,但我看不到它

我的 JS 代码是 -

function changeBg()     {     
let newBgColor = document.querySelector("body")      
console.log(newBgColor)      
newBgColor.style.backgroundColor = "white";      
}
The CSS Im hoping to change is -

     body {      
  font-family: 'Open Sans';     
  font-weight: normal;      
  max-width: 760px;      
  background-color: #ffe8d6;      
  margin: 0 auto;      
  color: rgb(193, 178, 164);      

  }
``   
I keep getting this error -
ReferenceError - newBgColor is not defined.

最佳答案

这是您可以执行的操作的示例,在 <head> 中加载 CSS并在页面末尾加载 JavaScript。

<!DOCTYPE html>
<html>

<head>
  <title>Body Bg Color</title>

  <style>
    body {
      font-family: 'Open Sans', sans-serif;
      font-weight: normal;
      max-width: 760px;
      background-color: #ffe8d6;
      margin: 0 auto;
      color: rgb(193, 178, 164);
      width: 100vw;
      height: 100vh;
    }
  </style>

</head>

<body>


  <script>
    function beigeBg() {
      let newBgColor = document.querySelector("body")
      console.log(newBgColor)
      newBgColor.style.backgroundColor = "beige";
    }

    beigeBg();
  </script>
</body>

</html>

关于javascript - 我试图用 JS 更改 CSS "body"属性的背景...我一直收到控制台错误 "newBgColor is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72028722/

相关文章:

javascript - 我将如何为我的游戏制作本地高分表?(Javascript)

javascript - 使用 jquery 或 javascript 从文本框和文本区域获取文本并保存在 cookie 值中

javascript - 对具有多个实例的每个单个元素的 jQuery 操作

javascript - Uncaught ReferenceError : "changing" is not defined (JavaScript)

javascript - 如果选择了输入并单击了按钮,则为 jQuery 条件

javascript - Phaser 2 - 如何检测我何时拖动另一个 Sprite ?

jquery - 如何在打开事件之前隐藏 jquery 对话框?

javascript - HTML 表单无法正常工作

javascript - 需要的javascript代码解释

swift - 从父类(super class)调用所有子类的函数