【问题标题】:Understanding last-child了解最后一个孩子
【发布时间】:2013-10-18 18:43:46
【问题描述】:

我有以下html结构:

<div class="decorator">
    <div class="EC_MyICHP_Item">
        <div class="text">
            <h3><a target="_blank" title="" href="#"></a></h3>
            text here text here text here text here text here text here 
        </div>
    </div>

    <div class="EC_MyICHP_Item">
        <div class="text">
            <h3><a target="_blank" title="" href="#"></a></h3>
            text here text here text here text here text here text here 
        </div>
    </div>

    <div class="EC_MyICHP_Item">
        <div class="text">
            <h3><a target="_blank" title="" href="#"></a></h3>
            text here text here text here text here text here text here 
        </div>
    </div>

    <div class="readmore"><a></a></div>
</div>

我试图通过使用 last-child 来选择 LAST EC_MyICHP_Item,但徒劳无功。 (CSS和jQuery)你能帮我吗?

谢谢。

【问题讨论】:

  • 我在代码中犯了一个错误:我刚刚添加了最后一个 div。我相信这是干扰,虽然它没有相同的类名。

标签: css jquery-selectors css-selectors


【解决方案1】:

您需要在选择器末尾使用:last-child

div.EC_MyICHP_Item:last-child

http://reference.sitepoint.com/css/pseudoclass-lastchild

示例http://jsfiddle.net/jasongennaro/zrufd/

请注意:这在早期版本的 IE 中不起作用。

编辑

根据关于添加最后一个div 的评论,它会产生干扰。你是对的。它确实会导致 :last-child 窒息……至少在我测试它的 Chrome 中。

如果您的 HTML 结构保持不变,即始终是三个 div.EC_MyICHP_Item,您可以这样做

.EC_MyICHP_Item:nth-child(3)

更新示例: http://jsfiddle.net/jasongennaro/zrufd/1/

编辑#2

不幸的是,EC_MyICHP_Item div 的数量各不相同

在这种情况下,我会使用 jQuery:

$('.EC_MyICHP_Item:last')

进一步更新示例: http://jsfiddle.net/zrufd/2/

【讨论】:

  • 我在代码中犯了一个错误:我刚刚添加了最后一个 div。我相信这是干扰,虽然它没有相同的类名。
  • 不幸的是 EC_MyICHP_Item div 的数量不同:/
  • 好吧@George。我认为 jQuery 现在是唯一的选择。请参阅我的更新答案。
【解决方案2】:

.EC_MyICHP_Item:last-child 应该可以正常工作。

重要的是要意识到E:last-child 的意思是“一个 E 元素,它是最后一个子元素”,而不是“E 元素的最后一个子元素”。

【讨论】:

    【解决方案3】:

    我添加 ID 仅用于测试目的。

    但是使用:last

    http://jsfiddle.net/aDbcW/1/

    【讨论】:

      【解决方案4】:

      .EC_MyICHP_Item:last-child 仅当 div 是其父 div 的最后一个子级时才有效。由于您将 div.readmore 作为父级的最后一个子级,因此您的选择器将不起作用。您需要改用.EC_MyICHP_Item:last-of-type

      编辑:在 jQuery 中,这将转换为 .EC_MyICHP_Item:last

      【讨论】:

      • 最后一个类型选择器不起作用(在小提琴中测试)我将尝试使用 jQuery 来支持跨浏览器
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2013-03-12
      • 2012-02-09
      • 1970-01-01
      • 2022-11-10
      • 2011-11-08
      相关资源
      最近更新 更多