[英]How do you change background color on td in CSS?
我正在尝试根据 tp1_value 更改表格单元格的背景颜色。 tp1_value 是从数据库表中选择的单元格值,它是 True 或 False。
如何使背景颜色在真时变为“绿色”,在假时变为“红色”? 在我单击表格单元格之前默认颜色为灰色,该表格单元格是 null 值。
我似乎无法在 css 上使用 if 语句。 :(
编辑:所以我想出了这个但它不起作用..如果我将条件更改为 (a1a = 'True')、(a1a = 'False'),无论 a1a 值为 True 还是错误的。 请帮忙。
<td id="a1"><div class="t">
<script>
var a1a = document.querySelector("#a1").value;
if (a1a === 'True') {
document.getElementById('a1').style.backgroundColor = 'green';
} else if (a1a === 'False') {
document.getElementById('a1').style.backgroundColor = 'red';
} else {
document.getElementById('a1').style.backgroundColor = 'black';
}
</script>
</div></td>
您必须根据您的服务器脚本语言(将与您的数据库对话)来执行此操作
例如,您将创建以下 2 个 styles:
#tp1_green {
background-color: green;
}
#tp1_red {
background-color: red;
}
该页面将根据您的服务器逻辑打印 styles(下面的 ASP 示例):
<tr>
<td id="tp1"><div class="t">
<label id="<%if dbvalue = "green" then%>tp1_green<%else if dbvalue = "red" then%>tp1_red<%end if%>"></label>
</div></td>
</tr>
考虑使用 javascript 来应用条件逻辑:
var tp1Cell = document.getElementById("tp1")
var tp1Value = document.getElementById("tp1_value").html
If (tp1Value === "True") {
tp1Cell.style.backgroundColor = 'green'
} else {
tp1Cell.style.backgroundColor = 'red'
}
假设 tp1_value 在任何条件下都是可变的,所以你必须根据结果设置你的代码,
这是一个片段,显示了 id 在真假之间变化的情况下的结果。
document.querySelector('.ftrue').addEventListener('click', function() { document.querySelector('label').setAttribute('id', "true"); }); document.querySelector('.ffalse').addEventListener('click', function() { document.querySelector('label').setAttribute('id', "false"); });
label#true { background: green; color:white; } label#false { background: red; color:white; }
<table class="t1"> <tr> <td id="tp1"><div class="t"><label id="tp1_value">[Text]</label></div></td> </tr> </table> <button class="ftrue">True</button> <button class="ffalse">false</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.