简短而甜蜜,这个可以运行吗?
if ( document.getElementById('box').style.background = "red") {
document.getElementById('box').style.background = "yello"
} else {
document.getElementById('box').style.background = "green"
}
问题所在
因此,假设一个 ID 为"box"的框在上述语句之前运行条件,将背景更改为红色,if 语句是否可以将框背景更改为黄色?这可能会令人困惑,但简而言之,您可以使用CSS样式条件来运行javascript块,然后更改该元素的css吗?
我认为答案是肯定的。但是我猜你的任务不对。您的意思是检查背景颜色当前为红色,然后将其更改为黄色? 我在 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"
}
只需向任何页面上的任何可见元素添加 id="box"
属性即可进行测试。
例如
在 Chrome devtool 的元素和控制台标签中:
-
将
id="box"
添加到此问题的标题中。 -
设置其背景并获取返回值。
var c = document.getElementById('box').style.background = "red"
.而c是"red"
.使用typeof c
,c是string
。
所以你的答案是肯定的,因为你可以使用string
作为条件。但请注意,如果带有id="box"
的目标元素不存在,您可能会TypeError
。
if (document.getElementById('box').style.backgroundColor === "red") {
document.getElementById('box').style.backgroundColor = "yellow"
} else {
document.getElementById('box').style.backgroundColor = "green"
}
#box {
width: 100px;
height: 100px;
background: red;
}
<div id="box" style="background-color: red;" ></div>