2011-10-28 107 views
1

比方说,我有以下的(2)的div:平均分配数目不详的儿童高度的DIV父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没有明确阐明的高度。

在正常情况下,对于第一示例中,我可以声明50像素(或50%)的每个内部的div的高度。而对于#2,我可以为每个内部div设置100px的高度(或25%)。

的问题是,我将有父DIV高度无限数量的儿童数目不详的div父母之内(有些人可能有一个孩子,而其他人可能有5个或更多)。所以,我需要一种方法让子div自动分配彼此之间的高度,而不管存在多少。

谢谢!

回答

2

http://jsfiddle.net/KQZZy/

$(".parent").each(function(){ 
    var $this = $(this); 
    var $children = $this.children(); 

    $children.height($this.height()/$children.length - 2); 
}); 

注意,- 2是调整,因为我对的div和你的情况可能是不必要的边界。

4

由子div的数量只要得到家长的高度,划分并设置其高度。

var $parent = $('div#parent'), 
    $children = $parent.children(), 
    child_height = $parent.height()/$children.size(); 

$children.height(child_height); 
3

简单的解决方法是使用display: table;。不幸的是,这留下了Internet Explorer 6及以下版本。但考虑如何易于阅读this jsfiddle是。

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... 
+0

我想你可能误解了这个问题。另外,做'$'('#auto-height')each(''从来没有道理,因为id应该是唯一的。 –

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/

我希望这有助于!

+0

在这里使用find也会给出任何可能存在的嵌套div。 。 –

+0

@JamesMontagne好一点;将编辑 – dSquared

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); 
    }); 
}); 
+0

'$(“#yourdiv”)各('是不是真的有效,'id's应该是唯一的也许类,而不是 –

+0

当然我是想给出一个。?。例如,不是完整的解决方案。 – aorcsik