2014-02-25 115 views
0

Iam正在研究項目,在此類情況下進行拍攝。更改父div高度取決於使用javascript的兒童絕對div高度

我需要我的父母div伸展其高度取決於子div。父高度固定爲400px;

#parent-div{ 
min-height:400px; 
width:250px; 
background-color:#333; 
position:relative; 
} 


#child-div{ 
position:absolute; 
height:auto; 
top: 0%; 

}

我需要我的孩子的div是absolute定位。

孩子div由表格內容組成,根據內容高度可能會增加。我需要我的父母div伸展相應。所以我需要一個解決方案,其中計算出兒童的渲染高度,並使父區段比兒童伸展得更多。

If rendered height of child div is 400px, I need my parent div to be 450px; 

我該怎麼做?

+0

讓我們瞭解您已經試過表演,我們可以幫你解決這個問題。 –

回答

0

如果試圖父div的寬度設置爲100%

#parent-div{ 
min-height:400px; 
width:250px;    <- 
background-color:#333; 
position:relative; 
} 

#parent-div{ 
min-height:400px; 
width:100%; 
background-color:#333; 
position:relative; 
} 

希望幫助你!

+0

我試過了,它沒有工作。所以我正在尋找js解決方案。 – user3335843

0

因爲你使用jQuery添加此javascript:

$().ready(function(){ 
    ch = $('#child-div').height(); 
    $('#parent-div').css({ 
     height : ch + 50 + 'px' 
    }) 
}); 

演示:JSFiddle

+0

這實際上工作正常。我應該離開這個$()。ready(function(),或者我應該添加一些像$(document).ready(function()? – user3335843

+0

不適用於我,我添加了console.log(ch);在那裏無論如何js解決方案我都嘗試他們都有這個相同的結果回聲「0」。 –

0
$(function(){ 
    var parent= $('#parent'); 
    var parentOffset = parent.offset(); 
    var bottom = 0; 
    parent.find('*').each(function() { 
     var elem = $(this); 
     var elemOffset = elem.offset(); 
     var elemBottom = elemOffset.top + elem.outerHeight(true) - parentOffset.top; 
     if (elemBottom > bottom) { 
      bottom = elemBottom; 
     } 
    }); 

    parent.css('min-height', bottom); 

}); 
相關問題