0

我有多个 div 使用相同的 html,高度可变。我正在尝试计算 div 的高度.content,然后使用该值来设置.sectionsdiv 的高度。目前,此函数仅影响其类型的最后一个 div。如何使此功能可重用,以便它适用于页面上的每个 div?

var currentHeight = 0;
jQuery(document).ready(function() {

    jQuery('.content').each(function() {
      currentHeight = jQuery(this).outerHeight();
    });

    jQuery('.sections').each(function() {
      jQuery(this).css('height', currentHeight/2);
    });

});

示例 HTML:

<div class="sections"></div>
  <div class="content">content with a height of 200px</div>
<div class="sections"></div>

other html....

<div class="sections"></div>
  <div class="content">content with a height of 400px</div>
<div class="sections"></div>

因此,前两个.sections将获得 100 像素的高度,后两个.sections将获得 200 像素的高度。

更新: 我找到了基于 Forty3 答案的解决方案!这可以写得更干吗?

Forty3 的解决方案对我有用,但做了一些小的调整:

// With the .content FOLLOWING the .section - use the following:
jQuery(document).ready(function() {

    jQuery('.bigImageSections').each(function() {

      var ic = jQuery(this).next('.translatedContent');
      if (ic.length > 0) {
        jQuery(this).css('height', jQuery(ic).outerHeight() / 2);
      }

      var ict = jQuery(this).prev('.translatedContent');
      if (ict.length > 0) {
        jQuery(this).css('height', jQuery(ict).outerHeight() / 2);
      }

    });
});
4

1 回答 1

0

遍历你的.section元素,根据内部元素的高度重新计算它们的高度.content

// If the .content was inside the .section - use the following
jQuery(document).ready(function() {

    jQuery('.sections').each(function() {
      var ic = jQuery('.content', this);
      if (ic.length > 0) {
        jQuery(this).css('height', jQuery(ic).outerHeight() / 2);
      }
    });
});

// With the .content FOLLOWING the .section - use the following:
jQuery(document).ready(function() {

    jQuery('.sections').each(function() {
      var ic = jQuery(this).next('.content');
      if (ic.length > 0) {
        jQuery(this).css('height', jQuery(ic).outerHeight() / 2);
      }
    });
});

编辑:忘记除以 2。

顺便说一句:我注意到在您的示例 HTML 中,您的.. 中.content没有包含您的内容,这是故意的吗?.section如果是这样,您是否预计.section元素会根据前面或后面的.content元素智能调整大小?

于 2018-01-19T22:32:18.623 回答