jquery - 同级 css 选择器没有改变

标签 jquery html css css-selectors

<分区>

所有 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/

上一篇:css - 关于垂直对齐 (CSS) 的困惑

下一篇:css - 为相同的 CSS 属性应用单独的过渡时间

相关文章:

javascript - 使用 jQuery 修改类

php - 再次在 wordpress 中添加自定义背景图像

html - 应该流到下一行的文本不会增加父框模型

javascript - 打开大弹出窗口时如何防止firefox滚动到页面底部

html - 如何将子 div 设置为父级的高度(100%)?

javascript - 查找包含选择器 id + 文本的元素

javascript - 如何使用 jQuery 选择没有类或 ID 的文本?

javascript - 通过预选下拉列表加载 Ajax 下拉列表

html - 希望文本叠加对其背景做出响应

javascript - 在 php 页面之间传递 javascript 值