jquery .each с функцией.outerHeight влияет на все div

У меня есть несколько div, используя один и тот же HTML, с переменной высотой. Я пытаюсь вычислить высоту див .content, затем используйте это значение, чтобы установить высоту .sections дела. В настоящее время эта функция влияет только на последний 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 получит высоту 100px, а последние два .sections получит высоту 200px.

ОБНОВЛЕНИЕ: Я нашел решение, основанное на ответе 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);
      }

    });
});

1 ответ

Беги через свой .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 элементы?

Другие вопросы по тегам