Изменить высоту класса с помощью JQuery для каждого элемента «foreach» - PullRequest
0 голосов
/ 16 апреля 2019

У меня есть foreach, который получает информацию из processwire.В каждой строке слева находится изображение (class = Img1), а справа описание внутри div (class = Test2).Я хочу измерить высоту как изображения, так и элемента, содержащего описание, выбрать самое большое и установить его для высоты элемента, содержащего изображение (class = Test1).Проблема с реальным кодом заключается в том, что на первой итерации наибольшая высота сохраняется и применяется ко всем строкам, а не только к первой.

Я знаю, что должен использовать итерационную функцию each ()Я пытался понять, как это работает, но мне это не удалось.Может ли кто-нибудь помочь мне, пожалуйста?

HTML

    <?php $Ser = $pages->get("name=services");?>
<section id="<?=$Ser->title;?>" class="mea-service-section section-padding-shorter">
  <?php $i = 0;
      foreach($Ser->ServicesRepeater as $Ser):
      $image = $Ser->ServicesRepeaterImage2;

      $colFirst = "";
      // if ($i%3 == 0) $colFirst = 'col_first'; //
      $i++; ?>
      <div class="container">

    <div class="row mt-10" style="display: flex;">


    <!-- Services Widget Section -->
    <div class='outer-row' id="<?=$Ser->ServicesRepeaterHeadline;?>">
      <div class="col-md-5 mea-title-section wow animated slideInLeft" data-wow-delay=".2s">
      <div class="media-left-center vertical-align Test1">
        <img src="<?=$image->url;?>" alt="<?=$image->description;?>" class="Img1 img-responsive center-block rcorners3">
      </div>
    </div>
    <div class="col-md-7 <?=$colFirst;?> single-service-widget wow animated fadeInUp" data-wow-delay=".3s">
      <div class="Test2">
        <div class="media-body">
          <h2 class="subtitle"><?=$Ser->ServicesRepeaterHeadline ?></h2>
          <p><?=$Ser->ServicesRepeaterDescription ?></p>
        </div>
      </div>
    </div>
    </div>

  </div>
</div>
<?php endforeach; ?>
</section>

JQuery

var divImgHeight = function() {
  var divHeight = $('.Test2').height();
  var imgHeight = $('.Img1').height();
  if (imgHeight < divHeight) {
    $('.Test1').css('height', divHeight+'px');
  } else {
    $('.Test1').css('height', imgHeight+'px');
  }
}

$(document).ready(function() {

  function resizeLinks(){
    divImgHeight();
  }
  $(window).on("resize", resizeLinks);
  resizeLinks();

    });

Фактическая страница в разработке: https://brightnode.io/en/services/

1 Ответ

0 голосов
/ 16 апреля 2019

Предполагая, что внешний div - это одна "строка", присвойте внешнему div класс, чтобы на него можно было ссылаться:

<div class='outer-row' id="<?=$Ser->ServicesRepeaterHeadline;?>">
  <div class="col-md-5 mea-title-section wow animated slideInLeft" data-wow-delay=".2s">
    <div class="media-left-center vertical-align Test1">
      <img src="<?=$image->url;?>" alt="<?=$image->description;?>" class="Img1 img-responsive center-block rcorners3">
    </div>
  </div>
  <div class="col-md-7 <?=$colFirst;?> single-service-widget wow animated fadeInUp" data-wow-delay=".3s">
    <div class="Test2">
      <div class="media-body">
        <h2 class="subtitle"><?=$Ser->ServicesRepeaterHeadline ?></h2>
        <p><?=$Ser->ServicesRepeaterDescription ?></p>
      </div>
    </div>
  </div>
</div>

затем выполните цикл по .outer-row и примените свой код к каждой строке, используя this для ссылки на строку, например:

$(".outer-row").each(function() { 

  // at this point "this" is each of the .outer-row divs in turn

  var divHeight = $('.Test2', this).height();
  // or
  var imgHeight = $(this).find('.Img1').height();

дает:

var divImgHeight = function() {
  $(".outer-row").each(function() { 
    var row = $(this);  
    var divHeight = $('.Test2', row).height();
    var imgHeight = $('.Img1', row).height();
    if (imgHeight < divHeight) {
      $('.Test1', row).css('height', divHeight+'px');
    } else {
      $('.Test1', row).css('height', imgHeight+'px');
    }
  });
}

$(document).ready(function() {
  function resizeLinks() {
    divImgHeight();
  }
  $(window).on("resize", resizeLinks);
  resizeLinks();
});

EDIT

Чтобы применить наибольшую высоту ко всем из них, вам сначала нужно пройтись по элементам, чтобы получить наибольшую высоту, а затем выполнить цикл по каждой строке для применения. Вы можете применить некоторые сочетания клавиш, но концепция та же.

var divImgHeight = function() {
  // get all the heights from .Test2/.Img1
  var heights = $(".outer-row .Test2,.outer-row .Img1").map(function() { return $(this).height(); }).toArray();
  // get the largest height
  var maxheight = Math.max.apply(Math, heights);

  // apply to all .Test1s
  $(".outer-row .Test1").css('height', maxHeight+'px');
}
...