垂直扩展元素以填充父级的剩余空间

时间:2016-05-16 15:45:30

标签: javascript jquery html

鉴于此标记和样式:

<div class="a">
  <div class="b">Fixed height</div>
  <div class="b">Fixed height</div>
  <div class="expand">Expand</div>
  <div>Fixed height</div>
</div>

.a {
  float: left; width: 100%; height: 500px;
}
.a>div {
  float: left; width: 100%;
}
.b {
  width: 50%;
}

我想展开.expand来填充父级中的空白区域。见附图。

当前尝试计算父项的当前高度,删除其height属性并将.expand的高度设置为这两个值的差异。如果有多个.expand兄弟姐妹,则高度除以它们的数量。

如果.expand也是一个列(在此示例中为.b),则会获得其父级高度的100%。

$(".expand").css({height:"auto"}).each(function() {
        var parent=$(this).parent();

        if($(this).is(".b")) {
            $(this).css("height",$(parent).innerHeight());
        } else {
            var siblings=$(parent).children(".expand");
            var siblingsTotalH=0;
            $(siblings).each(function() { siblingsTotalH+=$(this).outerHeight(); });            

            var currentH=$(parent).innerHeight();
            var currentCssH=$(parent).css("height"); //Save the value to restore it later
            $(parent).css("height","auto");

            var minH=$(parent).innerHeight()-siblingsTotalH;            
            var dif=(currentH-minH)/siblings.length;

            if(dif>0) $(this).css("height",dif);

            $(parent).css("height",currentCssH);            
        }
    });

这种方式有效但工作案例有限。 .expands不能是内联元素,而案例B需要不同的标记:

<div class="a">
      <div class="b">Fixed height</div>
      <div class="b">Fixed height</div>
      <div class="expand">
           <div class="b expand">Expand</div>
           <div class="b expand">Expand</div>
      </div>
      <div>Fixed height</div>
    </div>

我留下这个问题是为了看看是否有更合适的解决方案。

是否有任何简单的解决方案可以实现这一目标?或者有一个jQuery插件,这样做?我无法找到这个特殊情况。

这里有类似的问题,在这种情况下,我无法更改标记或使用display: table或CSS flex,因为它会混淆其他元素。我正在寻找JavaScript解决方案。

简化样式以显示易于阅读的示例。图像澄清包括其他类似情况(左,初始状态,正确的预期结果)。

这些是例子。关键在于扩展,无论其他元素是什么或如何排列。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用offsetHeights进行计算。这个小提示显示了如何做页眉和中间容器

https://jsfiddle.net/stevenkaspar/hk1escoj/

<div id='header'>
  header
  <p>
    another line
  </p>
</div>
<div id='container'>
  container
</div>

<div id='footer'>
  container
</div>
var resize = function(){
  var windwow_height = window.innerHeight;
  var footer_height = document.getElementById('footer').offsetHeight;
  var header_height = document.getElementById('header').offsetHeight;
  var container_height = windwow_height - (header_height + footer_height);

  document.getElementById('container').style.height = container_height + 'px';
}

window.onresize = resize;
resize();
相关问题