jQuery获取容器中内容的高度

时间:2016-01-27 15:01:37

标签: 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>
</div>

如何获得#container内容的真实高度?这些内联高度就是显示父高度可以是任何东西的示例。我想知道内容真正占用了多少。再次假设可能存在任意数量的子标签。

注意在上面的示例中,如果它们不是内联的,则真实高度是这些段落的高度。

5 个答案:

答案 0 :(得分:3)

不确定是否可以使用单个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

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;
     });

UPDATED FIDDLE

答案 1 :(得分:2)

尝试使用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>

答案 2 :(得分:1)

您可以使用jQuery的.height() - 函数:

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

获取匹配元素集中第一个元素的当前计算高度

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

获取匹配元素集中第一个元素的当前计算内部高度(包括填充但不是边框)

或者

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

获取匹配元素集中第一个元素的当前计算高度,包括填充,边框和可选边距

<强> Demo

答案 3 :(得分:0)

使用jQuery方法 $("selector").height(); 这将返回您的容器占用的数量。

答案 4 :(得分: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);