【问题标题】:How to reload a div for equal height child on window resize如何在窗口调整大小时为等高子项重新加载 div
【发布时间】:2017-04-28 19:03:07
【问题描述】:

我编写了脚本来赋予包装器的子元素相同的高度。它在页面加载时工作正常,但是当我调整大小或更改 ipad 的方向时..高度保持与页面加载期间相同。

$(window).on('load resize', function () {
     $('.equal-height-wrapper').each(function () {
     var heightArray = [];
     var allbox = $(this).find(".equal-height-box");
     $(allbox).each(function () {
     heightArray.push($(this).height());
     });
     var maxBoxHeight = Math.max.apply(Math, heightArray);
     $(this).find('.equal-height-box').css('height', maxBoxHeight);
     });
});

<div class="equal-height-wrapper">
  <div class="inner-wrapper">
    <div class="equal-height-box">

    </div>
    <div class="equal-height-box">

    </div>
  </div>
</div>

我想在子元素发生变化时更新它们的高度。到目前为止,我已经添加了溢出隐藏,以便隐藏任何重叠的文本。

我尝试将此脚本放在负载调整大小上,但没有任何区别。

【问题讨论】:

  • 您能否添加与您的问题相关的 HTML 和 CSS 部分?
  • 能否包含处理load resize事件并调用上述代码的代码
  • 我已经更新了代码

标签: javascript jquery css resize equal-heights


【解决方案1】:

将代码包装在命名函数中,以便您可以通过各种方式调用它。我会用$.ready 替换窗口.load。还添加了orientationchange 事件。然后你会得到类似的东西:

function setEqualHeight() {
  $('.equal-height-wrapper').each(function() {
    var heightArray = [];
    var allbox = $(this).find(".equal-height-box");
    $(allbox).each(function() {
    $(this).height("");  // remove previously set heights
    heightArray.push($(this).height());
    });
    var maxBoxHeight = Math.max.apply(Math, heightArray);
    $(this).find('.equal-height-box').css('height', maxBoxHeight);
  });
}

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

【讨论】:

  • 是的,我错过了重要的事情:删除之前设置的高度!它们是内联样式,比样式表或样式标签中的样式具有更多的 CSS 特异性(重要性),因此 jquery 将使用它们!无论如何,只有 css 的解决方案当然更好......但还是编辑了我的脚本
  • 不客气!顺便说一句,如果有很多调整大小和 cpu 负载是一个问题,你可能想要在调用 setEqualHeight() 时做一些速率限制
【解决方案2】:

为什么不只使用 CSS 呢? 像这样的东西可以工作......

(已更新为使用 FIXED 容器高度和未知容器高度)

/* For fixed container HEIGHT */
.container-1 {
    display: block;
    width:150px;
    background-color:yellow;   
    height:200px;
}
.child-1 {
    width: 30px;
    background-color: red;
    display: inline-block;
    vertical-align: top;
    top:0px;
    bottom:0px;
    height:100%;
}
/* FOR UNKNOWN CONTAINER HEIGHT */
.container-2 {
    display: table;
    width:150px;
    background-color:yellow;   
}
.child-2 {
    width: 30px;
    background-color: red;
    display: table-cell;
    vertical-align: top;
}

演示:http://jsfiddle.net/bkG5A/740/

您也可以考虑使用 CSS FLEX

【讨论】:

  • 是的..但是这里容器的高度为 200px。对我来说,高度不是固定的......它可以是任何东西
  • 移除容器的高度,仍然可以工作。我刚刚添加了一些额外的 CSS 以清楚地展示行为(例如高度和颜色。)我将更新代码,以保持必要性。
  • 刚刚检查了 jsfiddle..两个红色框的高度不等...我试图使两个红色框的高度相等
  • 你是对的。我再次更新,只使用 CSS 处理这两种情况。
  • 嘿,是的,它有效..但我有疑问..如果子元素不是直接子元素怎么办...我更新了问题中的 html。即使孩子不是直接孩子,该脚本实际上也可以工作..只是调整大小..它需要再次完成这项工作
猜你喜欢
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多