我一直在尝试使用一个函数来更改 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/