开发者

jQuery - watch for element height change

I have a element, which is absolute positioned and has a fixed height.

This element has a lot of child elements, which could change their contents, and in consequence their height. The problem is that the container element doesn't auto expand to fit its children (because开发者_StackOverflow社区 of it's fixed height and absolute position).

How can I can resize the main container to match its children height?


Assuming you can change the css, this can be done fairly simply in css. Instead of setting height simply set min-height and your element should expand thusly.

min-height


Optionally if you did want to/need to do it in jQuery something like the following would work:

html:

<div id='container'>
 <div class='child'>Content</div>
 <div class='child'>Content</div>
 <div class='child'>Content</div>
 <div class='child'>Content</div>   
</div>

CSS:

.child{
    height: 40px;
    background-color: red;
}
#container{
    height: 120px;
    background-color: gray;
    padding: 5px;
}

javascript:

var childHeight = 0
$('.child').each( function() {
    childHeight = childHeight + $(this).height();
})
$('#container').height(childHeight);

Working example:

http://jsfiddle.net/EcZZL/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜