HTML/CSS语句可以是Javascript条件吗?

mp.*_*peg 0 html javascript css

简短又甜蜜,这可以运行吗?

if ( document.getElementById('box').style.background = "red") {
    document.getElementById('box').style.background = "yello"
} else {
    document.getElementById('box').style.background = "green"
}
Run Code Online (Sandbox Code Playgroud)

问题

因此,假设一个ID为"box"的框具有在上述语句之前运行的条件,将背景更改为红色,if语句是否可以将框背景更改为黄色?这可能会令人困惑,但简而言之,您可以使用CSS样式条件,运行一个javascript块,然后更改该元素的CSS吗?

vic*_*oob 6

我认为答案是肯定的.但是我猜你的任务不对.你的意思是检查背景颜色是否为红色,然后将其更改为黄色?我在jsfiddle中测试过:https://jsfiddle.net/r3y72njf/24/ .您也可以在此处查看:https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp.还有一件事,在你的比较中,你必须使用'=='或'===','='表示赋值.

if ( document.getElementById('box').style.backgroundColor  === "red") {
    document.getElementById('box').style.backgroundColor  = "yelloy"
} else {
    document.getElementById('box').style.backgroundColor  = "green"
}
Run Code Online (Sandbox Code Playgroud)