[英]jQuery get height of the contents in a container
我什至不確定這是否可行,但我想獲取容器中內容的高度。 假設我有
<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;
}
如果您想知道為什么設置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;
});
嘗試使用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>
使用jQuery方法$("selector").height();
這將返回您的容器占用量。
var cc = 0;
$("#"+currenId2c+ "> .cc").each(function(){
var getDisplay = $(this).attr('dipslay')
getDisplay !=='inline'? (cc += $(this).outerHeight()) :0;
});
var cnt = cc;
console.log(cnt);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.