假设我有以下(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数量不限,父母的子女数量不明(有些可能有一个孩子,有些可能有5个或更多)。因此,我需要一种方法让子div自动分配彼此之间的高度,而不管存在多少。
谢谢!
答案 0 :(得分:4)
得到父母的高度,除以子div的数量并设定其高度。
var $parent = $('div#parent'),
$children = $parent.children(),
child_height = $parent.height() / $children.size();
$children.height(child_height);
答案 1 :(得分:3)
简单的解决方案是使用display: table;
。不幸的是,这遗漏了Internet Explorer 6及更低版本。但请考虑一下this jsfiddle是多么容易阅读。
答案 2 :(得分:2)
$(".parent").each(function(){
var $this = $(this);
var $children = $this.children();
$children.height($this.height() / $children.length - 2);
});
请注意- 2
是为了调整我在div上的边框,在你的情况下可能是不需要的。
答案 3 :(得分:0)
<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...
答案 4 :(得分:0)
浏览每个父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/
我希望这有帮助!
答案 5 :(得分:0)
下面的代码会调整#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);
});
});