使选定 元素 一致 高度

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

简介

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

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

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

如何使用它:

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

  1. <script src="/path/to/cdn/jquery.slim.min.js"></script>
  1. function mam_set_auto_height() {
  2. // reset sh-active class
  3. $('.sh-active').css('height', 'auto');
  4. $('.sh-active').removeClass('sh-active');
  5.  
  6. // get all elemets with same height data
  7. $ashElements = $("[data-same-height]");
  8. // loop through the elements
  9. $ashElements.each(function () {
  10. $element = $(this);
  11.  
  12. // skip if it's been configured already or not
  13. if ($element.hasClass('sh-active')) {
  14. return true;
  15. }
  16. // get group to set same height
  17. var _group = $element.attr('data-same-height');
  18.  
  19. // get group elements
  20. $groupElements = $('[data-same-height="' + _group + '"]');
  21.  
  22. // Cache the highest
  23. var highestBox = 0;
  24.  
  25. // loop throgh the group elements
  26. $groupElements.each(function () {
  27. // If this box is higher than the cached highest then store it
  28. if ($(this).height() > highestBox) {
  29. highestBox = $(this).height();
  30. }
  31. });
  32. // Set the height of all those children to whichever was highest
  33. $groupElements.addClass('sh-active').height(highestBox);
  34. });
  35. }

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

  1. <div data-same-height="group-1">
  2. ...
  3. </div>
  4.  
  5. <div data-same-height="group-1">
  6. ...
  7. </div>
  8.  
  9. <div data-same-height="group-1">
  10. ...
  11. </div>
  12.  
  13. ...

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

  1. mam_set_auto_height();

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

  1. $(window).on('load',function () {
  2. mam_set_auto_height();
  3. });
  4.  
  5. $(window).on('resize',function () {
  6. mam_set_auto_height();
  7. });

预览截图