javascript jquery查找所有divs孩子的总高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13048722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery finding the total height of all divs children
提问by loriensleafs
hey I have a div with 5 div's contained in it, I want to add all of their heights together,
嘿,我有一个包含 5 个 div 的 div,我想将它们的所有高度加在一起,
This is the solution I ended up using based off of Jeff's answer. Thanks for helping me out.
这是我最终根据杰夫的回答使用的解决方案。谢谢你的协助。
var ev_totalHeight = 0;
$("#events > div").each(function(){
ev_totalHeight += $(this).innerHeight();
});
function events_open() {
$("#events").animate({
"height": ev_totalHeight
}, 450 );
}
$("#events").click(function() {
events_open();
});
回答by Jeff
Heres a fiddle: http://jsfiddle.net/yj8sL/2/
这是一个小提琴:http: //jsfiddle.net/yj8sL/2/
$(function(){
var totalHeight = 0;
$("#parent > div").each(function(){
totalHeight += $(this).height();
});
alert("Total height of all divs: "+totalHeight);
});
As you see, there are 5 divs, with a height of 100px each, so the total height is 500px.
如您所见,有 5 个 div,每个高度为 100px,因此总高度为 500px。
EDIT: Your next problem (with the animate) is that you are not telling it what unit you are using (in your case, pixels):
编辑:你的下一个问题(动画)是你没有告诉它你使用的是什么单位(在你的情况下,像素):
$("#events").animate({
"height": ev_totalHeight+"px"
}, 450 );
回答by Paul Fleming
Something along these lines:
沿着这些路线的东西:
var height = 0;
$('#events > div').each(function(){
height += $(this).height();
});
// apply calculated height to another element
$('#myotherdiv').height(height + 'px');
回答by AGB
Loop through them all and add the height e.g.
循环遍历它们并添加高度,例如
var height;
$("#events").each(function() {
height += $(this).height();
});