簡體   English   中英

jQuery獲取容器中內容的高度

[英]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 請看這里

的jsfiddle

編輯

添加一個迭代器以排除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的.height()函數:

$('#container').height();

獲取匹配元素集中第一個元素的當前計算高度

要么

$('#container').innerHeight();

獲取匹配元素集合中第一個元素的當前計算的內部高度(包括填充,但不包括邊框)

要么

$('#container').outerHeight();

獲取匹配元素集合中第一個元素的當前計算高度,包括填充,邊框和可選邊距


演示

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM