html - 选择某种类型的最后一个 child

标签 html css css-selectors

<分区>

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

<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

最佳答案

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

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

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

没有计划引入previous sibling selector 甚至在 Selectors Level 4 中,我认为它们永远不会被引入,因为这违背了Cascading 的含义样式表。

但是有一个在 Level 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>

关于html - 选择某种类型的最后一个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125525/

相关文章:

javascript - Div 没有正确排列

php - IF 语句需要以一定的宽度显示文本并且只在主页上显示

css - SCSS中嵌套元素+元素选择器

html - CSS 上的不对称背景阴影

python - 使用selenium从元素获取src

javascript - 为每个第 2、5、8、11 等类元素添加边距

html - 悬停 DIV 时不使用边框

javascript - 使用 jQuery 动画缓入

javascript - 隐藏输入字段,除非选择特定变体 - Shopify

javascript - 为静态网站捆绑javascript和css? (网页包?)