无法在chrome中获得对象的真实高度/宽度

Cin*_*ird 9 jquery height google-chrome width

我有一个问题,如果我在css中设置图像高度并尝试获得高度/宽度,我会在不同的浏览器中得到不同的结果.有没有办法在所有浏览器中获得相同的维度?

你可以在这里找到一个实例<-Removed

这个概念是这样的:

CSS:
img{
  height:100px;
  }

Script:
$(document).ready(function(){
    $("#text").append($("#img_0").attr("height"));
    $("#text").append($("#img_0").attr("width"));
});
Run Code Online (Sandbox Code Playgroud)

输出Firefox:img height:100 img width:150

输出Chrome:img高度:100 img宽度:0

输出Chrome:img高度:100 img宽度:93?

我从StackOverflow尝试过这个:stackoverflow.com/questions/1873419/jquery-get-height-width

但仍然得到相同的结果

谁知道一个好的解决方案?

Nic*_*ver 24

图片未加载document.ready,您需要使用该window.load事件以确保它们存在,如下所示:

$(window).load(function(){
    $("#text").append($("#img_0").height());
    $("#text").append($("#img_0").width());
});
Run Code Online (Sandbox Code Playgroud)

这里有一个关于差异的快速阅读,重要的部分是图片被加载.


bra*_*jam 6

Nick Craver使用$(window).load()的答案是正确的,但图像也有一个load()方法,它允许更精细的粒度,特别是如果可能要加载多个图像.

  $(document).ready(function(){ 
    $("#top_img_0").load (function (){
      $("#text").append( "height: " + $("#top_img_0").attr("height")+"<br/>" );
      $("#text").append( "width: " + $("#top_img_0").attr("width")+"<br/>" );   
      }); 
  });
Run Code Online (Sandbox Code Playgroud)