选择:first-child或:last-child不包含某个特定类 [英] Select :first-child or :last-child that doesn't contain some specific class

查看:364
本文介绍了选择:first-child或:last-child不包含某个特定类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含5个项目的列表,并且我们要对第一个或最后一个孩子应用一些特定样式。但是这个列表的功能需要通过jQuery应用一个类来隐藏它的一些东西(我们叫它 .hide ),它会设置一个

Assume we're having a list with 5 items and we want to apply some specific styles to the first or the last child. But the functionality of this list will require to hide some of its items by applying through jQuery a class (let's call it .hide) which will set a display: none; on the targeted items.

应用于FIRST和LAST项是可见的,所以我想实现的是以某种方式跳过那些应用了 .hide 类的,

我已经尝试通过组合一些:not(.hide):first-child / :last-child 此外,尝试使用simbling选择器将最多适用于第一个孩子,但现在没有办法在css中选择以前的兄弟姐妹,所以这个解决方案不会覆盖最后一个孩子的问题。

I already tried to do this by combining some :not(.hide) and :first-child/:last-child pseudos, but it doesn't work. Also, trying to use simbling selectors will work at most for the first child, but there's no way right now to select a previous sibling in css so this solution will not cover the last child problem.

这里是一个jsfidle,你可以更好地理解我想要做什么:

Here's a jsfidle where you can better understand what I'm trying to do:

http://jsfiddle.net/3wgxt1oL/

HTML

HTML

<div class="hide">Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div class="hide">Item 5</div>

CSS

.hide {display: none;}
div:not(.hide):first-child,
div:not(.hide):last-child {color: red;}


推荐答案

不可能与CSS选择器。原因有两个:

As mentioned, this is not possible with CSS selectors. The reason is twofold:


  • :first-child :last-child 表示他们父母的第一个和最后一个孩子。它们不表示与选择器其余部分匹配的第一个和最后一个子元素。链接:not(.hide)简单地告诉选择器忽略该元素,如果它有 .hide 它不会更改选择器其余部分的含义。

  • :first-child and :last-child represent the first and last children of their parents, period. They do not represent the first and last child elements matching the rest of the selector. Chaining :not(.hide) simply tells the selector to ignore the element if it has the .hide class; it does not change the meaning of the rest of the selector.

There is currently no other pseudo-class available for the first or last (or nth) element matching an arbitrary selector.

由于您已经使用jQuery来应用 .hide 类,您可以使用它来应用另一个类到匹配:not(.hide)的第一个和最后一个元素,然后在CSS中定位这些额外的类。

Since you're already using jQuery to apply the .hide class, you can use it to apply another class to the first and last elements matching :not(.hide), then target those additional classes in your CSS.

这篇关于选择:first-child或:last-child不包含某个特定类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆