【发布时间】:2019-11-20 11:01:01
【问题描述】:
所以我试图查看一个单元格是否有红色背景,当我将测试放入输入框
并单击按钮时,我收到消息“这不是红色”。有人可以
向我解释一下如何让它说“这是红色的”吗?
var colors = ["rgb(255, 0, 0)"];
function testfunction() {
var location = document.getElementById("userinput").value;
if (document.getElementById(location).style.backgroundColor == colors[0]) {
alert("This is red");
} else {
alert("This is not red");
}
}
.red {
background-color: rgb(255, 0, 0);
}
<table>
<tr>
<td id="test" class="red"> a1 </td>
<td id="test2"> b1 </td>
</tr>
<tr>
<td id="test3"> a2 </td>
<td id="test4" class="red"> b2 </td>
</tr>
</table>
<input id="userinput" type="text">
<button id="button" onclick="testfunction()"> Button </button>
【问题讨论】:
-
因为
document.getElementById(location).style.backgroundColor不等于colors[0]。记录背景颜色以进行调试 -
这是什么?
id=t est为什么每个id都有空格? id 的不允许有空格。 -
Element.style为您提供为此元素定义的内联样式。但是你在css中设置了background-color。查看getComputedStyle() -
@Roy 这是第一个编辑器引入的错误。
-
这能回答你的问题吗? Get current applied style with JS
标签: javascript