首页 > 解决方案 > 为什么我的函数给我“这不是红色的”?

问题描述

所以我想看看一个单元格是否有红色背景,当我在输入框中输入测试
并单击按钮时,我收到“这不是红色的”消息。有人
可以向我解释一下如何让它说“这是红色的”吗?

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>

标签: javascript

解决方案


默认情况下node.style不会给你计算样式。您必须使用window.getComputedStyle(element)来检查计算样式。

所以下面的代码应该可以工作

var colors = ["rgb(255, 0, 0)"];

function testfunction() {
  var location = document.getElementById("userinput").value;
  if (getComputedStyle(document.getElementById(location)).backgroundColor == colors[0]) {
    alert("This is red");
  } else {
    alert("This is not red");
  }
}



推荐阅读