鉴于此标记和样式:
<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
sibling ,则高度除以他们的数量。
如果 .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 解决方案。
样式经过简化以显示易于阅读的示例。图片澄清包括其他类似情况(左,初始状态,右预期结果)。
这些都是例子。关键是要扩展,而不管其他元素是什么或它们是如何排列的。
最佳答案
您可以使用offsetHeights
进行计算。这个 fiddle 展示了如何制作页眉页脚和中间容器
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();
关于javascript - 垂直扩展元素以填充父元素的剩余空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257910/