2012-12-07 10 views
4

可能重复:
why jquery .height() get a different result on chrome?

我有一个<div>与CSS类myclass。 CSS类如下:

.myclass { 
    position: absolute; 
    width: 192px; 
    font-size: 11px; 
    background-color: #FFF; 
    padding: 15px 15px 0; 
    box-shadow: 0 1px 3px rgba(34, 25, 25, 0.4); 
    -moz-box-shadow: 0 1px 3px rgba(34, 25, 25, 0.4); 
    -webkit-box-shadow: 0 1px 3px rgba(34, 25, 25, 0.4);  
    display: block; 
} 

它没有指定高度。内容由PHP动态加载。在jQuery的$(document).ready(function() { });,我调试的div的高度:

console.log($('div.myclass').height()); // the result = 330 

HTML:

<div class="myclass"> 
<img src="image.png" /> 
<p>Text here text here</p> 
</div> 

但是,如果我用Inspect Element功能在谷歌浏览器,它显示531px。为什么有差异?我怎样才能得到531px的价值?

UPDATE$(this).outerHeight(); // 345px, as there is 15px margin

回答

12

尝试把窗口负载处理程序中的代码,也可以作为你的元素有15px padding属性,你应该使用outerHeight方法:

$(window).load(function(){ 
    console.log($('div.myclass').outerHeight()); 
}); 

注意outerHeight接受一个布尔值,false表示排除利润率和真实的方式增加保证金,还要注意outerHeight返回与类名的第一个匹配元素的高度。

+0

已经在'$(document).ready(function(){});' – Raptor

+1

@ShivanRaptor加载窗口没有准备好文档。 – undefined

+0

这个工程! '$(window).load'时,'$(this).outerHeight();'值是准确的。但为什么'$(document).ready'不起作用? – Raptor

4
console.log($('div.myclass').outerHeight()); 

的outherHeight也将考虑到空白和边距。

编辑:如果您不需要保证金,请改用innerHeight()

+0

我试过了。 'outerHeight()'增加了边距,但仍然缺少大约200px。它是否与DIV中的图像没有高度有关? – Raptor

+0

该元素只有15px的填充,它不能解决问题。 – undefined

+0

这可能是计算图像加载之前的高度。如果它始终是固定大小,则可以尝试在''标记中设置高度:http://jsfiddle.net/swVLf/(使用包含在“img'标记中的高度运行一次,然后将其移除以查看发生了什么......;)) – MassivePenguin

3

实际上是准确的。

  • height()功能会告诉你块元素的高度,没有空白和边距
  • innerHeight()功能会告诉你块元素的高度,以填充但没有保证金
  • outerHeight()函数告诉你的高度与填充和利润率,该块元件