我希望将父级的高度与其子级的总高度相匹配,因此内容不会从父级边框流出.我正在使用以下代码:
$("#leftcolumn").each(function(){
totalHeight=totalHeight+$(this).height();
});
Run Code Online (Sandbox Code Playgroud)
它会遍历所有div的孩子吗?有时候,有时它不起作用.
此外,我尝试了下面的代码,假设它会考虑所有的孩子.但结果很奇怪,并且从正确的结果中得到了两倍的高度.
$("#leftcolumn > *").each(function(){
totalHeight=totalHeight+$(this).height();
});
Run Code Online (Sandbox Code Playgroud)
提前致谢.
jAn*_*ndy 46
试试吧:
var totalHeight = 0;
$("#leftcolumn").children().each(function(){
totalHeight = totalHeight + $(this).outerHeight(true);
});
Run Code Online (Sandbox Code Playgroud)
http://api.jquery.com/outerHeight/采取margins
,paddings
并borders
进入计算应返回更可靠的结果.
另一种方法是计算元素内最顶部和最底部偏移之间的距离,这将考虑任何非静态定位元素.
我只在一个页面和环境中测试过这个,所以我不确定使用它有多安全.如果代码非常糟糕或者它值得一些改进,请发表评论.
var topOffset = bottomOffset = 0,
outer = true;
$el.children().each(function(i, e){
var $e = $(e),
eTopOffset = $e.offset().top,
eBottomOffset = eTopOffset + (outer ? $e.outerHeight() : $e.height());
if (eTopOffset < topOffset) {
topOffset = eTopOffset;
}
if (eBottomOffset > bottomOffset) {
bottomOffset = eBottomOffset;
}
});
var childrenHeight = bottomOffset - topOffset - $el.offset().top;
Run Code Online (Sandbox Code Playgroud)
如果你想忽略隐藏元素,你可以过滤掉它们:
$("#leftcolumn").children().filter(':visible').each(function(){
totalHeight += $(this).outerHeight();
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
39708 次 |
最近记录: |