首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery获取容器中内容的高度

jQuery获取容器中内容的高度
EN

Stack Overflow用户
提问于 2016-01-27 15:01:36
回答 5查看 10.1K关注 0票数 4

我甚至不确定这是否可能,但我想知道容器中内容的高度。让我们假设我

代码语言:javascript
复制
<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内容的真实高度?这些内联高度就像显示父级高度的例子一样。我想知道这些内容真正占据了多少。再次假设可以有任意数量的子标记。

注意,在上面的例子中,真正的高度是那些段落的高度,如果它们不是内联的话。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-01-27 16:18:38

不确定这是否可以使用单个jQuery/javascript函数来完成。但是这个片段可能很有用

HTML

代码语言:javascript
复制
 // 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

代码语言:javascript
复制
// 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

代码语言:javascript
复制
 p{
    margin:0px;
        }

看这儿如果您想知道为什么要设置margin:0

JSFIDDLE

编辑

添加一个迭代器以排除inline元素。此外,.each还对具有cc类的元素进行迭代。这样您就可以使inline不具有cc类。

下面是在添加元素高度之前检查元素的display类型的片段。

代码语言:javascript
复制
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;
     });

更新小提琴

票数 3
EN

Stack Overflow用户

发布于 2016-01-27 15:03:34

您可以使用.height()-functions of jQuery:

代码语言:javascript
复制
$('#container').height();

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

代码语言:javascript
复制
$('#container').innerHeight();

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

代码语言:javascript
复制
$('#container').outerHeight();

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

演示

票数 2
EN

Stack Overflow用户

发布于 2016-01-27 15:09:42

尝试使用window.getComputedStyle(/* DOM element */).getPropertyValue("height")

代码语言:javascript
复制
console.log(window.getComputedStyle($("#container")[0]).getPropertyValue("height"))
代码语言:javascript
复制
<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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35040795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档