<分区>
<分区>
所有 ID 为 1 的 tr
及其下的所有 ID 2 之前的颜色应该相同。检查示例。但是ID 2之后不会变。
这是我的代码:
[id="1"], [id="1"] ~ tr {
background-color: blue;
}
[id="2"], [id="2"] ~ tr {
background-color: red;
}
<table>
<tbody>
<tr id="1"><td>foo</td></tr> <!-- Blue -->
<tr><td>foo</td></tr> <!-- Blue -->
<tr><td>foo</td></tr> <!-- Blue -->
<tr id="2"><td>foo</td></tr> <!-- Red -->
<tr><td>foo</td></tr> <!-- Red -->
<tr id="1"><td>foo</td></tr> <!-- Blue (But is Red) -->
<tr><td>foo</td></tr> <!-- Blue (But is Red) -->
<tr><td>foo</td></tr> <!-- Blue (But is Red) -->
<tr><td>foo</td></tr> <!-- Blue (But is Red) -->
</tbody>
</table>
最佳答案
给定 html
at Question 你可以使用相邻的兄弟选择器 +
, !important
[class="1"],
[class="1"] ~ tr {
background-color: blue;
}
[class="2"],
[class="2"] + tr {
background-color: red !important;
}
<table>
<tbody>
<tr class="1">
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr class="2">
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr class="1">
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
</tbody>
</table>
或者,使用 jQuery 的 .nextUntil()
、.add()
$(".1").nextUntil(".2").add(".1").addClass("blue");
$(".2").nextUntil(".blue").add(".2").addClass("red");
.blue {
background-color: blue;
}
.red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="1">
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr class="2">
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr class="1">
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
<tr>
<td>foo</td>
</tr>
</tbody>
</table>
关于jquery - 同级 css 选择器没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39259685/