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

时间:2019-11-20 11:01:01

标签: javascript

因此,我尝试查看单元格是否具有红色背景,当我在输入框中输入test并单击按钮时,我收到消息“这不是红色”。有人可以
向我解释我怎么能说“这是红色的”吗?

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>

2 个答案:

答案 0 :(得分:4)

默认情况下,function onOpen() { SlidesApp.getUi().createMenu('Extra tools').addItem('Rename Slides document', 'renameSlides').addToUi(); } function renameSlides() { var result = SlidesApp.getUi().prompt('Enter the new name for the slides document'); var newName = result.getResponseText(); if (!newName) return; var fileId = SlidesApp.getActivePresentation().getId(); DriveApp.getFileById(fileId).setName(newName); } 不会为您提供计算样式。您必须使用window.getComputedStyle(element)来检查计算的样式。

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

node.style

答案 1 :(得分:0)

使用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>

相关问题