我希望每个前一行都有表格样式。任何时候白色单元格悬停在其上时,其上方的绿色标题都应采用不同的背景颜色。任何帮助将不胜感激。
$("#customers tr:odd").hover(function() {
$(this).prev().css({
"background-color": "red !important"
});
}, function() {
$(this).prev().css({
"background-color": "black !important"
});
});
#customers {
width: 100%;
}
#customers td {
border: 1px solid #ddd;
}
#customers tr:hover {
background-color: yellow;
}
#customers th {
text-align: center;
background-color: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<table id = "customers">
<tr>
<th colspan = "3"> Words</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr colspan=3>
<th colspan = "3"> More Words </th>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Christina Berglund</td>
<td>Sweden</td>
</tr>
</table>
</body>
</html>
最佳答案
您可以通过添加/删除类来执行类似的操作。您必须指定 td/th
才能向它们添加 css
。我正在使用 removeClass
方法来减少与两个 !important
css
属性的混淆。
$("#customers tr:odd").hover(function() {
$(this).prev().find('th').removeClass('black');
$(this).prev().find('th').addClass('red');
}, function() {
$(this).prev().find('th').removeClass('red');
$(this).prev().find('th').addClass('black');
});
#customers {
width: 100%;
}
#customers td {
border: 1px solid #ddd;
}
#customers tr:hover {
background-color: yellow;
}
#customers th {
text-align: center;
background-color: #4CAF50;
color: white;
}
.red {
background-color: red !important;
}
.black {
background-color: black !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<table id="customers">
<tr>
<th colspan="3"> Words</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr colspan=3>
<th colspan="3"> More Words </th>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Christina Berglund</td>
<td>Sweden</td>
</tr>
</table>
</body>
</html>
关于javascript - HTML 表格样式 previous sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50516199/