我正在计算 children
高度,以将滚动条添加到容器中。但它并不完美。谁能帮我完美地计算 child 的高度?
这是我的代码:
var p= "</p>Some testing text</p>";
var getAllHeight = function (content) {
var allHeight = 0;
$('#container').children().not('.content').each(function(){
allHeight += $(this).outerHeight(true);
});
return allHeight;
}
var addHeight = function () {
var content = $('.content');
var allHeight = getAllHeight(content);
var rest = $('#container').innerHeight() - allHeight;
if(content.outerHeight() > rest) {
content.css('height', (content.outerHeight() - allHeight ));
}
console.log(allHeight, content.height(), content.outerHeight(),content.innerHeight())
};
$('button').click(function(){
$('.content').append(p);
addHeight();
});
<div id="container">
<div>
<h2>Heading</h2>
</div>
<div>
<h2>Heading</h2>
</div>
<div class="content">
</div>
<div class="footer">
Footer
</div>
<div class="button"><button>Add</button></div>
</div>
最佳答案
这是由于 collapsing margins 引起的 CSS 问题(阅读“Parent and first/last child” case)关于 div>h2
结构。由于 div
容器没有任何内边距、边距或边框,它们的边距会折叠以容纳内边距。简单的解决方法是在它们或边框上设置一些填充或将 h2
设置为 inline-block。
另一个问题是,当没有足够的空间时,您应该将 content
高度设置为 rest
。
if (content.outerHeight() > rest) {
content.css('height', rest);
}
关于javascript - 如何完美计算 `children' s`的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391300/