【问题标题】:nth-child selecting wrong elementnth-child 选择了错误的元素
【发布时间】:2012-07-24 14:58:42
【问题描述】:

对于这个特定站点,当我通过 CSS 或 jQuery 使用 nth-child 时,“nth-child”选择器捕获了错误的元素。我在调用的选择器之前得到了一个孩子:

.home article:nth-child(3) {} //captures 2nd child

这似乎是在捕获第二个孩子。如果我尝试:

.home article:nth-child(1) {} //captures nothing

这不捕获任何元素。在 jQuery 中,它显示为一个空数组。这是我正在开发的开发网站。谢谢。

http://heilbrice.designliftoff.com/

【问题讨论】:

  • 嗯.. 不知道为什么会这样。你试过 $('.home article').eq(1); ?
  • 你能重现这是一个 JSFiddle 吗? jsfiddle.net/nBfdX 似乎在 Safari 中工作。你在什么浏览器上测试?

标签: jquery css jquery-selectors css-selectors


【解决方案1】:

在您的站点中,您有一个 clearfix div,它是容器内其父元素的第一个子元素,因此您的第一个 article 实际上是 第二个 子元素,而不是第一个子元素:

<div class="row-main clearfix">
    <div class="clearfix"></div>  <!-- .row-main.clearfix > :nth-child(1) -->

    <article id="post-" class=""> <!-- .row-main.clearfix > :nth-child(2) -->

在 CSS 中,您可以使用 :nth-of-type() 代替第三个 article 元素:

/* Select the 3rd article in its parent within .home */
.home article:nth-of-type(3) {}

奇怪的是,jQuery does not support :nth-of-type(),因此对于跨浏览器解决方案,您必须选择带有从零开始的索引的 :eq()

// Select the 3rd article within .home
$('.home article:eq(2)')

【讨论】:

  • 啊哈。感谢您指出空 div 正在这样做。我删除了所说的 div 并将记住这一点。谢谢。
  • :eq() 修复了我的应用在装有 iOS 8.2 的 Safari/iPad 上运行的问题。我一直在使用 :nth-child() ,它适用于 iOS 8.1 和所有其他主要浏览器。 :nth-child(2) 选择器返回一个长度为 0 的 jQuery 对象,而实际上有 2 个元素。
  • @normc:哇,多么奇怪的案例。我希望它在 GM 之前得到解决。
猜你喜欢
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
相关资源
最近更新 更多