【问题标题】:Get the height of two nested boxes dynamically with jquery height?使用jquery高度动态获取两个嵌套框的高度?
【发布时间】:2012-09-23 00:26:33
【问题描述】:

我想动态获取框的高度(在我的示例中为黄色背景) - 取决于其内容的长度。所以如果它有一个长文本,它的高度会增加。这个黄色盒子有一个父容器(在我的例子中是蓝色背景)。

我不明白为什么它们的高度相同 - 即100

蓝色框应该有更大的数字,因为它有 padding top 20pxpadding bottom 20px。因此,如果黄色框为 100,则蓝色框应为 140

jquery,

// Set the object.
var object = $(".box");
//var object_height = parseInt(object.css('min-height'),10) || parseInt(object.css('height'),10);
var object_height = object.height();

var scrollable = $(".scrollable");
//var scrollable_height = parseInt(scrollable.css('min-height'),10) || parseInt(scrollable.css('height'),10);
var scrollable_height = scrollable.height();

alert(object_height);
alert(scrollable_height);

html,

<div class="box">

    <div class="scrollable">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

</div>

来自jsfiddle的链接。

任何想法如何正确?

【问题讨论】:

    标签: jquery css height


    【解决方案1】:

    你应该使用outerHeight() 方法,它计算高度+边距/填充

    【讨论】:

      【解决方案2】:

      你可以使用outerHeight()方法。

      获取匹配元素集中第一个元素的当前计算高度,包括填充、边框和可选的边距。返回值的整数(不带“px”)表示,如果在一组空元素上调用,则返回 null。

      object.outerHeight()
      

      http://jsfiddle.net/GMtBa/

      【讨论】:

        【解决方案3】:

        您应该使用outerHeight() 来获得正确的高度值。

        // Set the object.
        var object = $(".box");
        var object_height = object.outerHeight();
        
        var scrollable = $(".scrollable");
        var scrollable_height = scrollable.outerHeight();
        
        alert(object_height);
        alert(scrollable_height);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-05
          • 2011-03-28
          • 1970-01-01
          • 2014-07-05
          • 2021-08-23
          • 2023-04-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多