jquery - 获取前一个多个div的高度

时间:2015-01-27 06:04:09

标签: jquery

如何获得像这样的多个div的高度:

<div class="alert"></div>
<div class="alert"></div>
<div class="alert"></div>

然后将其添加到每个div的top属性中。 这是他们的身高:

.alert {height:15px;}

所以加载后它将是:

<div class="alert"></div>
<div class="alert" style="top:15px"></div>
<div class="alert" style="top:30px"></div>

我只能设法获得前一个div的高度而不是之前的另一个div:

 $('.alert').each(function () {
       var posTop = $(this).prev('.alert').innerHeight();
       $(this).css({ top: posTop + 'px' });
   });

请。谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用变量存储累计最高值

var top = 0;
$('.alert').each(function () {
    var posTop = $(this).prev('.alert').innerHeight();
    if (top) {
        $(this).css({
            top: top + 'px'
        });
    }
    top += $(this).innerHeight();
});

演示:Fiddle

答案 1 :(得分:1)

如果所有div的高度相同,你可以试试这个:

$('.alert').each(function (index) {
   var posTop = $(this).prev('.alert').innerHeight()*index;
   $(this).css({ top: posTop + 'px' });
});

如果他们不是,你真的需要累积高度计算,你可以尝试这样的事情:

$('.alert').each(function () {
   var heightAbove = 0;
   var posTop = $(this).prevAll('.alert').each(function(){
       heightAbove += $(this).innerHeight();
   });
   $(this).css({ top: heightAbove+ 'px' });
});

答案 2 :(得分:1)

我建议使用prevAll()选择之前的所有提醒。

像这样:jsfiddle

  $('.alert').each(function () {
       var top = 0;
       $(this).prevAll('.alert').each(function(c) {
           top += $(this).innerHeight();
       })
       $(this).css({ top: top + 'px' });
   });