高度在 jQuery 中的 resize() 上不会改变

Height does not change on resize() in jQuery

本文关键字:改变 jQuery 中的 resize 高度      更新时间:2023-09-26

我有 4 个不同高度的div 容器。我希望每当我加载页面或调整窗口大小时,它们都具有相同的高度。我给每个div提供了类要求,并尝试了以下jQuery代码:

<script type="text/javascript">
        $(document).ready(adjustRequirement);
        $(window).resize(adjustRequirement);
        function adjustRequirement(){
            var maxHeight = -1;
            $('.requirement').each(function() {
                maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
            });
            $('.requirement').each(function() {
                $(this).height(maxHeight);
            });
        }
</script>

现在,每当我加载页面(或使用 F5 刷新(时,这都可以工作,但是当我调整窗口大小时它不起作用。我做错了什么?这是一个小提琴。

发生这种情况是因为您在第一次运行函数时设置了固定高度,这样每个div的高度将始终相同。由于div 默认具有overflow: visible即使文本超出div,也会显示文本。

试试这个,我添加了一行,它重置了div的高度,以便它调整以适应内容$(this).css('height', 'auto');

  $(document).ready(adjustRequirment);
  $(window).resize(adjustRequirment);
  function adjustRequirment(){
      var maxHeight = -1;
      $('.requirement').each(function() {
          $(this).css('height', 'auto');
          maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
      });
      $('.requirement').each(function() {
          $(this).height(maxHeight);
      });
  }
你也可以

使用 jquery-match-height。只需下载并实现jquery.matchHeight.js

$(document).ready(function() {
  $(function() {
    $('.requirement').matchHeight();
  }
});

它非常易于使用,也适用于 Rezise。