Javascript jQuery获取容器中内容的高度
我甚至不确定这是否可行,但我想得到容器中内容物的高度。让我们假设我有Javascript jQuery获取容器中内容的高度,javascript,jquery,html,css,jquery-ui,Javascript,Jquery,Html,Css,Jquery Ui,我甚至不确定这是否可行,但我想得到容器中内容物的高度。让我们假设我有 <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 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>
这里有一些文字
这里有一些文字
如何获得容器内容的真实高度?这些内联高度只是一个示例,显示父高度可以是任何东西。我想知道这些内容真正占据了多少。再次假设可能有任意数量的子标记
注意在上面的示例中,如果这些段落没有内联,则真实高度是这些段落的组合高度 您可以使用jQuery的-函数:
$('#container').height();
获取匹配元素集中第一个元素的当前计算高度
或
获取匹配元素集中第一个元素的当前计算内部高度(包括填充,但不包括边框)
或
获取匹配元素集中第一个元素的当前计算高度,包括填充、边框和可选边距
使用jQuery方法
$(“选择器”).height()代码>
这将返回容器占用的空间。尝试使用窗口。getComputedStyle(/*DOM元素*/)。getPropertyValue(“高度”)
console.log(window.getComputedStyle($(“#容器”)[0]).getPropertyValue(“高度”)
这里有一些文字
这里有一些文字
不确定是否可以使用单个jQuery/javascript
函数完成此操作。但是这个片段可能很有用
HTML
如果您想知道为什么设置margin:0
编辑
添加迭代器以排除inline
元素。还有。每个都在具有cc
类的元素上迭代。因此,您可以使inline
不具有cc
类
下面是在添加元素高度之前检查元素类型的一段代码
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;
});
你甚至在网上搜索过解决方案吗?所以你不是说你想知道它的100%高度。或者说你的浏览器窗口是800px高的,它告诉你800px,但实际上,尽管你在容器上设置了不同的高度,但下面两行使用了多少像素?当然,我在网上搜索过了。我已经找了两天了!如果你不明白这个问题,你不需要投票否决。不,我不在乎把%转换成px!我想知道较大父级中内容的高度(不是父级的高度,而是内容的组合高度)。只是一个小小的疑问,为什么它是安慰200px,但在您使用chroome dev的工具悬停在DOM上时,您可能会看到div的高度。child是68px,div#容器高度等于屏幕的高度?但如果孩子是内联的呢?这只适用于块显示项正确吗?仍然是一个有缺陷的答案。内联块、包裹的内联子对象、浮动的子对象等等都被打断。我认为真正的解决方案是在所有子对象的边上减去最小和最大y坐标。但我不知道这是否必须与容器中的内容物相抗衡
$('#container').outerHeight();
// 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>
// 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>' );
p{
margin:0px;
}
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;
});
var cc = 0;
$("#"+currenId2c+ "> .cc").each(function(){
var getDisplay = $(this).attr('dipslay')
getDisplay !=='inline'? (cc += $(this).outerHeight()) :0;
});
var cnt = cc;
console.log(cnt);