CSS中:nth-child和JQuery:eq的区别

$("li:nth-child(n)")选择器与$("li:eq(n)")选择器的不同之处在于:
$("li:eq(n)")选择器只匹配一个元素,并且是所有匹配到的元素中的第n+ 1个元素(索引index从0开始算起);
$("li:nth-child(n)")选择器则先选择该元素所有父元素的第n个子元素,再判断是否满足要求(序号n从1开始算起),如果是就选择,否则不选择(满足条件的可能有多个)。

 $("li:eq(-n)")选择倒数第n个元素,$("li:eq(-0)")选择正数第一个元素,$("li:eq(-1)")选择倒数第一个元素。

以下例子摘自https://blog.pivotal.io/labs/labs/css-first-child-nth-child-and-last-child-are-not-like-eq

 if we had a snippet of HTML like

<div>
    <div id="bar1" class="foo"></div>
    <div id="bar2" class="foo"></div>
    <div id="bar3" class="foo"></div>
</div>

Then the selector .foo:nth-child(2)will match the div #bar2. If we insert another element at the front of the container:

<div>
    <p>Shift!</p>
    <div id="bar1" class="foo"></div>
    <div id="bar2" class="foo"></div>
    <div id="bar3" class="foo"></div>
</div>

And again we select .foo:nth-child(2), we match the div #bar1 because the 2nd child of the container also matches .foo.

Thus, in this second example, if we try .foo:nth-child(1) or the equivalent .foo:first-child, we will not match any elements because the first child element in that container — the p tag — does not match .foo.

Likewise, :nth-child can match children in multiple containers. In the HTML snippet:

<div>
    <p>Shift!</p>
    <div id="bar1" class="foo"></div>
    <div id="bar2" class="foo"></div>
    <div id="bar3" class="foo"></div>
</div>

<div>
     <div id="quux" class="foo"></div>
</div>

the selector .foo:last-child will match the divs #bar3 and #quux; but .foo:first-child or .foo:nth-child(1) will only match #quux because the first child of the first container is, again, not a .foo.

转载于:https://www.cnblogs.com/goingforward/p/5355238.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值