【问题标题】:Repeated class container to take the height of last-child position and height重复类容器取最后一个子位置的高度和高度
【发布时间】:2012-10-24 23:09:31
【问题描述】:

我有一个重复的 div 容器 class="content" ,其中包含绝对定位的 div。

.content{
   width: 960px;
   margin: 0 auto;
   padding-bottom: 20px;
   position: relative;
   overflow: auto;
}

 .article0{
   width: 300px;
   position: absolute;
}

 .article1{
   width: 230px;
   position: absolute;
   top: 80px;
}

 .article2{
   width: 230px;
   position: absolute;
}

 .article3{
   width: 230px;
   position: absolute;
   margin-bottom: 20px;
   top: 500px;
}

据说容器 class="content" 在同一个页面中重复了很多次:

<div class="content">
<div class="article1"></div>
<div class="article2"></div>
<div class="article3"></div>
</div>

我要做的是为容器提供每个具有类 .content 的容器中最后一个子项的高度和顶部位置。我已经尝试了下面的代码,但没有任何结果,容器始终只获得相同的高度值,我猜只能来自最后一个或第一个容器的最后一个孩子?想不通!

$(function(){
var $box = $('.content');
var lastChildPos = $(':last-child', $box).position().top;
var lastChildHeight = $(':last-child', $box).height();

$box.height(lastChildPos + lastChildHeight);

});

【问题讨论】:

    标签: jquery position containers css-position css-selectors


    【解决方案1】:

    enter code here如果有多个实例,您将需要这样的东西:

    $('.content').each(function(){
    
        var lastChildPos = $(':last-child', $(this)).position().top;
        var lastChildHeight = $(':last-child', $(this)).height();
    
        $(this).height(lastChildPos + lastChildHeight);
    
    });
    

    这样它将它应用到盒子的每个实例,$(this) 获取与每个容器相关的变量。

    注意::last-child 将选择父容器中类型的最后一个子级。也许你想试试:

    var lastChildPos = $(this).find('div:last-child').position().top;
    

    【讨论】:

    • 无论如何都应该为 +1 发帖:P
    • 谢谢瑞克,我以前试过每一个都没有结果。尝试了您的代码,现在它得到第一个孩子的高度(!)忽略顶部位置!找不到问题所在!
    • 通过彻底检查结果,我发现对于前 3 个具有类 '.content' 的容器,它获取第一个孩子的高度,忽略它的顶部定位,而对于只有一个的最后一个容器孩子,高度是孩子的身高+顶部位置。想不通!有什么想法吗?
    • 那简直太完美了!经过测试和工作,“div”也是该职位所必需的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2014-09-17
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多