[英]Equally distribute the height of an unknown number of children divs inside a parent div
假設我有以下(2)個div:
例子1
<div style="height:100px;">
<div>1</div>
<div>2</div>
</div>
范例#2
<div style="height:400px;">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
我想自動平均分配子div的高度,而無需特別說明高度。
在正常情況下,對於第一個示例,我可以為每個內部div聲明50px(或50%)的高度。 對於#2,我可以為每個內部div聲明高度為100px(或25%)。
問題是,我的父母div高度將無限制,而父母中的子div數目也將未知(有些可能有一個孩子,而另一些可能有5個或更多)。 因此,我需要一種使子div自動在彼此之間分配高度的方法,而不管其存在多少。
謝謝!
只需獲得父母的身高,除以孩子的div數並設置他們的身高即可。
var $parent = $('div#parent'),
$children = $parent.children(),
child_height = $parent.height() / $children.size();
$children.height(child_height);
簡單的解決方案是使用display: table;
。 不幸的是,這遺漏了Internet Explorer 6及更低版本。 但是請考慮一下這個jsfiddle的易讀性。
$(".parent").each(function(){
var $this = $(this);
var $children = $this.children();
$children.height($this.height() / $children.length - 2);
});
請注意, - 2
用於調整div上的邊框,在您的情況下可能不需要。
<div id="auto-height" style="height:400px;">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
function sortNumber(a,b) {
return a - b;
}
function maxHeight() {
var heights = new Array();
$('#auto-height').each(function(){
$(this).css('height', 'auto');
heights.push($(this).height());
heights = heights.sort(sortNumber).reverse();
$(this).css('height', heights[0]);
});
}
$(document).ready(function() {
maxHeight();
})
$(window).resize(maxHeight);
Try with this...
遍歷每個父div,獲取子div的總數,然后將父母的身高除以它們; 像這樣:
<div class="parentDiv" style="height:500px;">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="parentDiv" style="height:200px;">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
$('.parentDiv').each(function(index, record){
var t = $(this).children().length;
var h = ($(this).height() / t);
$('div', this).css('height', h+'px');
});
這將遍歷每個div,並根據父母的身高更新子div的大小。
這是一個顯示實際效果的小提琴: http : //jsfiddle.net/krEYR/1/
我希望這有幫助!
下面的代碼將以相同的高度調整#yourdiv的所有子div的大小:
$("#yourdiv").each(function() {
var ydh = $(this).height(),
num = $(this).children("div").size(),
dh = ydh / num,
ah = 0;
$(this).children("div").each(function(i) {
var h;
if (i + 1 == num) { // last item
h = ydh - ah;
} else {
h = Math.round((i + 1) * dh);
}
$(this).height(h);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.