重复的类容器取最后一个子位置和高度的高度

时间:2012-10-24 14:02:15

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

我有一个重复的div容器类=“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;
}

正如所说容器类=“内容”在同一页面中重复多次:

<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);

});

1 个答案:

答案 0 :(得分:1)

enter code here如果有多个实例,您需要这样的内容:

$('.content').each(function(){

    var lastChildPos = $(':last-child', $(this)).position().top;
    var lastChildHeight = $(':last-child', $(this)).height();

    $(this).height(lastChildPos + lastChildHeight);

});

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

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

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