简体   繁体   English

为什么我的 function 给我“这不是红色的”?

[英]Why does my function give me “this is not red”?

So I'm trying to see if a cell has a red background, when I put test in the inputbox因此,当我将测试放入输入框中时,我试图查看单元格是否具有红色背景
and click the button, I receive the message "this is not red".并单击按钮,我收到消息“这不是红色的”。 Could someone please有人可以请
explain to me how I could make it say "this is red"?向我解释如何让它说“这是红色的”?

 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>

By default node.style wont give you computed styles.默认情况下node.style不会给你计算出的 styles。 You have to use window.getComputedStyle(element) to check computed styles.您必须使用window.getComputedStyle(element)来检查计算的 styles。

So following code should work所以下面的代码应该可以工作

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");
  }
}


Use getComputedStyle() to get the actual style used at runtime.使用getComputedStyle()获取运行时使用的实际样式。 The style property of the element will only give you information on the inline style of the element.元素的style属性只会为您提供有关元素内联样式的信息。

 var colors = ["rgb(255, 0, 0)"]; function testfunction() { var location = document.getElementById("userinput").value; var style = getComputedStyle(document.getElementById(location)); if (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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM