我有一段代码:
<style>
[contenteditable]:hover, [contenteditable]:focus {
background: #D7D7FF;
}
</style>若要使表格中单元格的背景在悬停或聚焦时更改颜色,请执行以下操作。
现在,其中一列的名称是Status。如果状态是late,意味着该单元格的值是= "Late",我希望背景更改为#FFD7D7。我该如何用javascript来写这个呢?
因为这个<style>是在html文件的开头,而不是CSS里面,所以我有点迷惑,不知道该怎么做。
任何帮助都是非常感谢的!
发布于 2013-06-06 01:14:37
$('.status').on('blur keyup paste', function() {
$this = $(this);
$(this).css('background', ($this.text() == 'Late') ? 'red' : 'inherit');
});其中每个状态单元格都有status类
发布于 2013-06-06 01:23:05
如果您不想使用jQuery,下面是用JavaScript编写的代码
http://jsfiddle.net/u72yF/3/
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“字符串,其他字符串被忽略。
如果您所说的着色是指悬停着色而不是常量着色(我演示过的),请删除底部的注释,它实现了这一点。
发布于 2013-06-06 03:38:40
一种可能性随之而来。使用jQuery可以更清楚地表达这一点,但由于您没有提到它,我们将在这一点上使用JavaScript:
<!DOCTYPE html>
<html>
<head>
<style>
[contenteditable]:hover, [contenteditable]:focus {
background: #D7D7FF;
}
.late {
background-color: #FFD7D7;
}
</style>
<script type="text/javascript">
function checkStatus(ev) {
var statusField = document.getElementById("status-field");
if (statusField.textContent == 'Late') {
statusField.className += " late";
} else {
statusField.className = statusField.className.replace(/(?:^|\s)late(?!\S)/g , '');
}
return true;
}
</script>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
<tr>
<td contenteditable="true">Juan Carlos</td>
<td id="status-field" contenteditable="true" onblur="return checkStatus()">Early</td>
</tr>
</table>
</body>
</html>https://stackoverflow.com/questions/16945411
复制相似问题