javascript - 为什么我的函数给我“这不是红色的”?
问题描述
所以我想看看一个单元格是否有红色背景,当我在输入框中输入测试
并单击按钮时,我收到“这不是红色的”消息。有人
可以向我解释一下如何让它说“这是红色的”吗?
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>
解决方案
默认情况下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");
}
}
推荐阅读
- reactjs - 使用 formik 滚动到第一个无效字段并 useRefs 做出反应
- python - 分配和使用具有相同条件的变量而不会收到警告
- c# - c#有关于格式大小和调整大小的问题
- python - 由于 pandas 列的差异,datetimetime 的变化
- javascript - jquery.min.js:9600 XHR 加载失败:POST
- python - 使用 Selenium 和 Scrapy 抓取所有下一页
- css - 使用 CSS / SVG 动画(绘制)波浪线
- ceph - 如何将新目录绑定到使用 ceph orch 部署的 ceph 容器中
- css - tailwindcss 没有在断点内使用我的自定义类
- php - 如何在 php mySQL 中更新当前日期时间