鑑於這種標記和樣式:豎直擴展的元素,以填補父母的剩餘空間
<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解決方案。
樣式被簡化以顯示一個易於閱讀的例子。圖像澄清包括其他類似的情況(左,初始狀態,預期的正確結果)。
這些都是例子。無論其他要素是什麼或者如何安排,關鍵在於擴展。
謝謝你,這是一個好主意,但問題是不管什麼其他的因素有或者他們是如何安排擴大。 – Gabriel