我什至不确定这是否可行,但我想获取容器中内容的高度。假设我有
<div id="container" style="min-height:100vh">
<div class="child">
<p>Some text here</p>
</div>
<div class="another-child">
<p>Some text here</p>
</div>
</div>
如何获取#container
内容的真实高度?这些内联高度只是一个例子,显示父级高度可以是任何东西。我想知道内容真正占据了多少。再次假设可能有任意数量的子标签。
注意 在上面的示例中,真实高度是那些段落的组合高度(如果它们不是内联的)。
最佳答案
不确定这是否可以使用单个 jQuery/javascript
函数来完成。但是这个片段可能很有用
HTML
// Added a common class to all child element of div#container
<div id="container" style="min-height:100vh">
<div class="child cc">
<p>Some </br>text here</p>
</div>
<div class="another-child cc">
<p>Some text here</p>
</div>
</div>
JS
// Loop through all child element using common class to get the total height
var cc = 0;
$("#container > div.cc").each(function(){
cc += $(this).outerHeight();
});
$('#height').append('<p>'+ cc+'</p>' );
CSS
p{
margin:0px;
}
Look here如果你想知道为什么设置 margin:0
编辑
添加一个迭代器来排除 inline
元素。 .each
也在迭代具有 cc
类的元素。所以你可以让 inline
没有 cc
类。
这是在添加高度之前检查元素的 display
类型的片段。
var cc = 0;
$("#container > .cc").each(function(){
var getDisplay = $(this).attr('dipslay') // Check the display attribute
// Using ternary operator
getDisplay !=='inline'? (cc += $(this).outerHeight()) :0;
});
关于javascript - jQuery 获取容器中内容的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040795/