根据jQuery中另一个类的大小设置每个类的高度

时间:2016-02-04 19:24:00

标签: jquery each

我有多个(可能无限制)"绝对"不同高度的类,但下面的代码设置EACH" relative" div到第一个绝对元素的高度。每个绝对div都是不同的高度,所以我需要循环并将每个相对div设置为其绝对div的高度。

HTML

      <div class="relative">
          <div class="absolute">
           <p>content here, which will be variable, so the heights will not always be the same</p>
          </div>
      </div>

Jquery的:

$( document ).ready(function() {
    var current_height = 0;
    $('.absolute').each(function() {
        current_height = $('.absolute').height();
    });
    $('.relative').each(function() {
        $('.relative').height(current_height);
    });
});

CSS:

  #relative {
   position: relative;
   display: block;
   width: 100%;
  }

 #absolute {
   position: absolute;
   display: block;
   overflow:hidden;
  }

 #relative,
 #absolute {
    width: 100%;
   max-width: 820px;
  }

2 个答案:

答案 0 :(得分:1)

在第一个current_height函数之外定义的.each()变量会被每次迭代覆盖。你只需要一个循环就可以修改第二个.each()函数,如下所示:

$('.absolute').each(function() {
     current_height = $(this).height();
     $(this).parent().height(current_height);
});

答案 1 :(得分:0)

我的建议是使用jQuery函数高度而不是每个:

$(function () {
  $('.relative').height(function(index, height) {
    //(this.querySelectorAll('.absolute')[0]).setAttribute('style','height:' + height + 'px');
    // or  in jQuery
    $(this).find('.absolute').css('height',  height + 'px');
  });
});
#relative {
  position: relative;
  display: block;
  width: 100%;
}

#absolute {
  position: absolute;
  display: block;
  overflow:hidden;
}

#relative,
#absolute {
  width: 100%;
  max-width: 820px;
}
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>

<div class="relative">
    <div class="absolute">
        <p>content here, which will be variable, so the heights will not always be the same</p>
    </div>
</div>
<div class="relative">
    <div class="absolute">
        <p>content here, which will be variable, so the heights will not always be the same</p>
    </div>
</div>
<div class="relative">
    <div class="absolute">
        <p>content here, which will be variable, so the heights will not always be the same</p>
    </div>
</div>
<div class="relative">
    <div class="absolute">
        <p>content here, which will be variable, so the heights will not always be the same</p>
    </div>
</div>