我想让 JavaScript 检查我的 css 代码并返回我,如果背景颜色 = #222327 它将把背景颜色更改为 #29fd53 但如果旧背景颜色 = #29fd53 它将把背景颜色更改为 #222327
我的Js代码
function changeBgC(){
var body = document.getElementsByTagName("body")[0];
var computedStyle = window.getComputedStyle(body)
var bodyBackgroundValue = computedStyle.getPropertyValue("background-color")
console.log(bodyBackgroundValue);
if (bodyBackgroundValue == "#222327") {
document.querySelector('body').style.backgroundColor = "#29fd53"
} else {
document.querySelector('body').style.backgroundColor = "#222327"
}
}
.body{
width: 100%;
height: 100vh;
min-height: 100vh;
background: #222327;
}
<div class="box">
<button onclick="changeBgC()" class="menuButton">≣</button>
</div>
我只是尝试使用 i++(我在 html 代码上使用 onclick),但它只会将背景颜色更改为 #29fd53。当我再次按下按钮时,它没有执行任何操作。
这是我尝试的
function changeBgC(){
var i = 0
if (i % 2 === 0){
document.querySelector('.body').style.backgroundColor = "#29fd53"
console.log(i);
i+=1
}else{
document.querySelector('.body').style.backgroundColor = "#222327"
i+=1
}
}
最佳答案
您的问题在于在函数作用域内设置 i 变量。所以每次你调用changeBgC()时它都会设置i = 0。
在函数之外声明 i ,它应该可以工作
let i = 0;
function changeBgC(){
if (i % 2 === 0){
document.querySelector('.body').style.backgroundColor = "#29fd53"
console.log(i);
i+=1
}else{
document.querySelector('.body').style.backgroundColor = "#222327"
i+=1
}
}
关于javascript - 检查 JavaScript 中的 CSS 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75898254/