兄弟姐妹css选择器没有改变

时间:2016-08-31 22:02:21

标签: jquery html css css-selectors

ID 2之前的所有tr及其下的所有[id="1"], [id="1"] ~ tr { background-color: blue; } [id="2"], [id="2"] ~ tr { background-color: red; }应该是相同的颜色。检查示例。但在ID 2之后它不会改变。

这是我的代码:

<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>
term_id

2 个答案:

答案 0 :(得分:2)

在问题中给出html您可以使用相邻的同级选择器+!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>

答案 1 :(得分:0)

保持简单。使用蓝色单元格默认为表​​格设置样式,并使用红色类来覆盖所需的位置。

&#13;
&#13;
.example-table td {
  background-color: blue;
}

.example-table .red td {
  background-color: red;
}
&#13;
<table class="example-table">
  <tbody>
    <tr>
      <td>foo</td>
    </tr>
    <tr >
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr class="red">
      <td>foo</td>
    </tr>
    <tr class="red">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;