【问题标题】:Why does my function give me "this is not red"?为什么我的函数给我“这不是红色的”?
【发布时间】: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


【解决方案1】:

默认情况下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");
  }
}


【讨论】:

    【解决方案2】:

    使用getComputedStyle() 获取运行时使用的实际样式。元素的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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      相关资源
      最近更新 更多