当高度为auto时,jQuery OuterHeight / Height返回错误的高度值

时间:2016-04-01 14:54:03

标签: jquery css

当CSS高度设置为自动时,如何获取填充文本的div对象的完整高度?

我尝试过OuterHeight,它仍然不是div对象的全高。

JSFiddle:https://jsfiddle.net/zerolfc/jg8s5oq3/3/

jQuery的:

$('div').find('*').each(function(ti,tv){
var c = parseInt( $(tv).css('font-size') ) / 2;
c = Math.floor( c );
c = ( c < 8 ? 8 : c );
$(tv).css('font-size', c + 'px');
});

console.log($('div').outerHeight(true));

CSS:

div { display: block; width: 640px; height: auto; }
p { font-size: 24px; }

HTML:

<div>
<p>This is a textbox that you can add text to suit your design and alter.This is a textbox that you can add text to suit your design and alter.</p>
<p>This is a textbox that you can add text to suit your design and alter.This is a textbox that you can add text to suit your design and alter.</p>
<p>This is a textbox that you can add text to suit your design and alter.This is a textbox that you can add text to suit your design and alter.</p>
<p>This is a textbox that you can add text to suit your design and alter.This is a textbox that you can add text to suit your design and alter.</p><p>This is a textbox that you can add text to suit your design and alter.This is a textbox that you can add text to suit your design and alter.</p><p>This is a textbox that you can add text to suit your design and alter.This is a textbox that you can add text to suit your design and alter.</p>
</div>

1 个答案:

答案 0 :(得分:1)

为我提供小提琴中的正确值。

来自http://api.jquery.com/outerheight/

$('div').outerHeight(true) = [height of the $('div') + margin of $('div')]

但是根据您当前的css规则,您的$('div')元素没有任何边距。

这意味着, $('div').outerHeight(true)将返回$('div')的实际高度,没有任何边距。

在您的情况下,所有后续3的值将是相同的。

  • $('div').outerHeight(true)
  • $('div').outerHeight()
  • $('div').css('height')