【问题标题】:jQuery: get height of child element when parent height is 0pxjQuery:当父高度为0px时获取子元素的高度
【发布时间】:2012-05-31 09:10:27
【问题描述】:

我有一个包含文本的 div,该文本仅在某些情况下显示在另一个 div 中。用于此的 HTML 很简单,如下所示:

<div id='parent'>
  <div id='child'>
    Some text inside child div
  </div>
</div>

样式看起来像:

#parent{ display:none; height:0px; }

使用 jQuery,我想获得子元素的高度,就像 div 在父元素之外一样。

以下 javascript 返回 0,我希望大约是 15。

var child_height = $('#child').height();
alert(child_height);

【问题讨论】:

  • 对我来说很好用。确保您在 文档准备好之后执行此操作。 jsfiddle.net/mattball/EnZtq
  • 工作得很好jsfiddle.net/zjpav/1
  • 除了 Matt Ball 评论 -> 在 FF 和 Chrome 中返回 20,在 IE 7 中返回 19。
  • 在您的代码中,#parent 实际上很可能是 display: none,在这种情况下它会返回 0。
  • 请参阅更新。我似乎忘记添加 display:none

标签: jquery height parent-child


【解决方案1】:

尝试所有这些并正常工作:

console.log($('#child').outerHeight());

console.log($('#child').css('height'));

console.log($('#child').height());

根据你的编辑:

var height = $('#parent').css({visibility: 'hidden', display : 'block'}).find('#child').height();

$('#parent').css({visibility: 'hidden', display: 'none'});

console.log(height);

DEMO

【讨论】:

    【解决方案2】:

    您可以暂时显示隐藏的父母,然后将其隐藏:

    // .parents means it will search through all parents, not just first hidden
    var hiddenParents = $("#child").parents(":hidden").show();
    var childHeight = $("#child").height();
    hiddenParents.hide();
    
    alert(childHeight);
    

    http://jsfiddle.net/zjpav/3/

    【讨论】:

      【解决方案3】:
      var child_height = $('#child').outerHeight();
      alert(child_height);​
      

      Demo

      尽管在 FF 10 上,您的原始代码运行良好。

      根据评论更新:

      对于隐藏字段,它将返回零,您可以执行以下操作:

      jQuery('#parent').css('display','block');
      var child_height = $('#child').outerHeight();
      alert(child_height);
      
      child_height = $('#child').height();
      alert(child_height);
      jQuery('#parent').css('display','none');
      

      Demo

      【讨论】:

        【解决方案4】:

        我注意到您说:“在另一个 div 内仅在某些情况下显示”。如果父 div 有display: none;(例如,如果您使用多个 jQuery 函数中的任何一个隐藏它,这就是它的最终结果),那么子 div 的高度将返回为 0。

        【讨论】:

        • 不是我想听到的,但我想你是对的。但是,正如您在其他答案中看到的那样,该问题有一些“解决方法”。感谢您的意见!
        猜你喜欢
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        • 1970-01-01
        • 2011-08-05
        • 2014-09-14
        • 2015-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多