使选定 元素 一致 高度

  • 源码大小:5.07KB
  • 所需积分:1积分
  • 源码编号:19JP-3655
  • 浏览次数:297次
  • 最后更新:2023年07月07日
  • 所属栏目:布局
本站默认解压密码:19jp.com 或 19jp_com

简介

现在有很多方法可以解决现代web开发中的等高元素。最好的两种方法是使用CSS flexbox和Grid Layout。

但是,如果您正在寻找一种跨浏览器的解决方案,以使某些元素(如div)具有统一的高度,那么本文非常适合您。

这是一个简单而轻量级的jQuery函数,可以用来使所选元素具有相同的高度。它的工作原理是计算元素的高度差,然后设置所有其他元素的高度以匹配该差,从而确保所有元素都具有相同的高度。

如何使用它:

1.主要功能是循环浏览一组中的所有元素,并将所有这些孩子的身高设置为最高者。复制下面的代码段,并在加载最新的jQuery库后插入它们。

<script src="/path/to/cdn/jquery.slim.min.js"></script>
function mam_set_auto_height() {
  // reset sh-active class
  $('.sh-active').css('height', 'auto');
  $('.sh-active').removeClass('sh-active');

  // get all elemets with same height data
  $ashElements = $("[data-same-height]");
  // loop through the elements
  $ashElements.each(function () {
      $element = $(this);

      // skip if it's been configured already or not
      if ($element.hasClass('sh-active')) {
          return true;
      }
      // get group to set same height
      var _group = $element.attr('data-same-height');

      // get group elements
      $groupElements = $('[data-same-height="' + _group + '"]');

      // Cache the highest
      var highestBox = 0;

      // loop throgh the group elements
      $groupElements.each(function () {
          // If this box is higher than the cached highest then store it
          if ($(this).height() > highestBox) {
              highestBox = $(this).height();
          }
      });
      // Set the height of all those children to whichever was highest
      $groupElements.addClass('sh-active').height(highestBox);
  });
}

2.添加数据高度相同属性指定给将具有相同高度的元素。

<div data-same-height="group-1">
  ...
</div>

<div data-same-height="group-1">
  ...
</div>

<div data-same-height="group-1">
  ...
</div>

...

3.拨打主要_自动_重量()文档上的函数已准备就绪。

mam_set_auto_height();

4.重新初始化主要_自动_重量()页面加载和调整大小。

$(window).on('load',function () {
  mam_set_auto_height();
});

$(window).on('resize',function () {
  mam_set_auto_height();
});

预览截图