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

Set the height of each class depending on the size of another class in jQuery

我有多个(可能无限)"absolute" 类 的不同高度,但下面的代码将每个 "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;
  }

在第一个 .each() 函数之外定义的 current_height 变量在每次迭代时都会被覆盖。你只需要一个循环就可以取消第二个 .each() 函数,像这样:

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

我的建议是使用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>