【问题标题】:Select last child of a certain kind [duplicate]选择某种类型的最后一个孩子[重复]
【发布时间】:2016-02-02 01:45:26
【问题描述】:

我在列表中有一个列表,在内部列表中我需要选择最后一个列表项。内部列表如下所示:

<ol>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li class="x">...</li>
</ol>

但我必须忽略类 x 的项目。 DEMO

li li:not(.x):last-child {
   color: red;
}

我希望C 是红色的,但它不起作用。有人可以向我解释问题是什么,如果可能的话,解决方案会很棒:) Thnx

【问题讨论】:

  • 你的预期输出是什么?
  • 我已经更新了问题。希望现在很清楚
  • 不,:last-child 不能这样工作。它不能选择最后一个没有 x 的孩子。它始终指向该父母的最后一个孩子。所以你的选择器会选择最后一个元素,如果它没有作为 x 的类。否则,它不会选择任何内容。
  • 我相信你已经知道了,但是如果 .x 是每个列表项的最后一个类,你可以使用 nth-last-child 定位 c,(或任何在 .x 之前的) (2)jsfiddle.net/Hastig/sky44bfo/8
  • 不,你不能。在这种情况下,您唯一能做的就是使用nth-last-child。最好改变你的逻辑。请记住,没有previous sibling 选择器

标签: html css css-selectors


【解决方案1】:

正如我在my answer here 中解释的那样,:last-child 选择器不能这样工作。此选择器仅指向一个元素,并且始终是其父元素的最后一个子元素。选择的子项不会根据附加到选择器的其他条件而更改。唯一受附加条件影响的是最后一个子元素本身是否被选中。

下面的选择器只是意味着只有当它没有类x时才选择最后一个子li元素而不是选择最后一个没有类的li子元素有类 x.

li li:not(.x):last-child {
   color: red;
}

即使在选择器级别 4 中也没有计划引入 先前的兄弟选择器,我认为它们永远不会被引入,因为这与 级联 的含义背道而驰样式表。

然而,第 4 级中指定的选择器可以解决这样的情况,它是 :nth-last-match 伪选择器。对于您的情况,它最终可能类似于以下内容:

li li:nth-last-match(1 of :not(.x))

我假设nth-last-match 将允许否定选择器,因为没有提及它是无效的even though :matches(:not(...)) is said to be invalid。它有可能被标记为无效,在这种情况下我们仍然会发现很难选择这些元素。

根据latest Editor's Draft of the spec,似乎:nth-last-match 选择器不再在范围内(并且已包含在:nth-last-child 选择器中)。因此,选择器将改为:

li li:nth-last-child(1 of :not(.x))

它还谈到了另一种可能对这种情况有用的方法。它是:has 伪选择器。

li li {
  color: red; /* apply the styling which needs to be set to the last child without class x */
}
li li:has( ~ li:not(.x)) { /* this selects all li which have a sibling whose class is not x */
  color: black; /* override the style for these alone and set them to the default */
}

注意:这只是草稿,可以更改。


一种可能的解决方案是使用 jQuery(或 JavaScript)找出满足条件的最后一个元素,然后为其设置所需的样式或类。

$(document).ready(function() {
  $('li ol').map(function() {
    return $(this).children().not('.x').get(-1);
  }).css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol>
  <li>
    <ol>
      <li>A</li>
      <li>B</li>
      <li class="x">X</li>
    </ol>
  </li>
  <li>
    <ol>
      <li>A</li>
      <li>C</li>
      <li class="x">X</li>
    </ol>
  </li>
  <li>
    <ol>
      <li>A</li>
      <li>D</li>
      <li class="x">X</li>
    </ol>
  </li>
  <li>
    <ol>
      <li>A</li>
      <li>D</li>
      <li class="ex">X</li>
    </ol>
  </li>
</ol>

【讨论】:

    猜你喜欢
    • 2014-04-26
    • 2017-03-07
    • 2019-03-28
    • 2015-02-07
    • 1970-01-01
    • 2018-07-16
    • 2018-11-08
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多