使用javascript根据孩子的绝对div高度更改父div高度
问题描述:
我正在研究这样的情况的项目.
Iam working on project where I cam across the situation like this.
我需要我的父div根据孩子的div拉伸其高度.父级高度固定为400px;
I need my parent div stretch its height depending on the child div. The parent height is fixed for 400px;
#parent-div{
min-height:400px;
width:250px;
background-color:#333;
position:relative;
}
#child-div{
position:absolute;
height:auto;
top: 0%;
}
我需要将我的孩子div定位为absolute
.
I need my child div to be absolute
positioned.
子div由表内容组成,其中高度可能根据内容而增加.我需要我的父母div相应地伸展.因此,我需要一个解决方案,在该解决方案中,将计算子级的渲染高度,并使父div的拉伸度超过子级.
The child div consists of table contents where the height may increase depending on the contents. I need my parent div stretch accordingly. So i need a asolution where the rendered height of child is calculated and make the parent div stretch extra than child.
If rendered height of child div is 400px, I need my parent div to be 450px;
我该怎么做?
答
$(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);
});