我甚至不确定这是否可能,但我想知道容器中内容的高度。让我们假设我
<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内容的真实高度?这些内联高度就像显示父级高度的例子一样。我想知道这些内容真正占据了多少。再次假设可以有任意数量的子标记。
注意,在上面的例子中,真正的高度是那些段落的高度,如果它们不是内联的话。
发布于 2016-01-27 16:18:38
不确定这是否可以使用单个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;
}看这儿如果您想知道为什么要设置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;
});发布于 2016-01-27 15:03:34
您可以使用.height()-functions of jQuery:
$('#container').height();获取匹配元素集合中第一个元素的当前计算高度。
或
$('#container').innerHeight();为匹配元素集中的第一个元素获取当前计算的内部高度(包括填充但不包括边框)。
或
$('#container').outerHeight();获取匹配元素集合中第一个元素的当前计算高度,包括填充、边框和可选边距。
发布于 2016-01-27 15:09:42
尝试使用window.getComputedStyle(/* DOM element */).getPropertyValue("height")
console.log(window.getComputedStyle($("#container")[0]).getPropertyValue("height"))<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="container" style="min-height:100vh">
<div class="child" style="height:100%">
<div class="another-child">
<p>Some text here</p>
</div>
<div class="another-child">
<p>Some text here</p>
</div>
</div>
</div>
https://stackoverflow.com/questions/35040795
复制相似问题