我有这段代码:
<style>
[contenteditable]:hover, [contenteditable]:focus {
background: #D7D7FF;
}
</style>
让表格中的单元格背景在鼠标悬停或获得焦点时更改颜色。
现在其中一列的名称是 Status。如果状态已晚,意味着该单元格的值为 =“迟到”,我希望背景更改为 #FFD7D7
.我如何用 javascript 编写这个?
自此 <style>
在 html 文件的开头而不是在 CSS 中我有点迷路,不知道该怎么做。
非常感谢任何帮助!
最佳答案
如果你不想使用 jQuery,这里是 JavaScript 代码
color = function() {
var table = document.getElementById('myTable');
var trList = table.getElementsByTagName('tr');
// index of the status column
var index = -1;
for (var i = 0; i < trList.length; i++) {
var tdList = trList[i].getElementsByTagName('td');
if (index < 0) {
// we need to find out the status column index first
for (var j = 0; j < tdList.length; j++) {
if (tdList[j].id == 'statusColumn') {
index = j;
break;
}
}
}
if (tdList[index].innerHTML.trim() == 'Late') {
// for constant coloring
trList[i].style.background = '#FFD7D7';
// for on hover coloring
//trList[i].onmouseover = function() {
// this.style.background = '#FFD7D7';
//}
//trList[i].onmouseout = function() {
// this.style.background = '';
//}
}
}
}
我假设,代码不知道哪一列是状态列,因此包含一个检测(通过 id“statusColumn”)。然后仅在该列中搜索“Late”字符串,忽略其他字符串。
如果您所说的着色是指悬停着色而不是恒定着色(我已经演示过),请删除底部的注释,它实现了这一点。
关于javascript - 当值 = "Late"时更改单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16945411/