2012-11-16 70 views
1

我正在处理一个插件,它需要我在加载后获取图像的宽度和高度,而不管图像的尺寸是如何确定的。jQuery获取图像宽度/高度加载容器

<img src=".." width="500" height="500" />    <!-- works fine --> 
<img src=".." style="width: 500px; height: 500px;" /> <!-- works fine --> 
<img src=".." width="500" />        <!-- only gives me width --> 
<img src=".." style="width: 500px;" />     <!-- only gives me width --> 
<img src=".." style="width: 500px; height: auto;" />  <!-- only gives me width --> 
<img src=".." />           <!-- doesn't work at all --> 

我试图加载图像后获取其尺寸,但我只能够得到图像的实际大小,而不是在它的网页上显示的大小。

img.innerWidth(); 

我也曾尝试:

$('<img/>').hide().attr('src',img.src).load(function() { 
    img.Owidth = $(this).width(); 
    img.Oheight = $(this).height(); 
}).appendTo($('body')); 

和:

$("<img/>").attr("src", img.attr("src")).load(function() { 
    img.width = this.width; 
    img.height = this.height; 
}); 

其中在得到做了很好的工作使用,以获得宽度/高度

代码IM我是图像的原始大小,但不是加载和显示时的大小。

+0

插件或您的代码必须抓取width属性,而不是查找元素的宽度。 – Andy

+0

你使用什么代码来获得宽度和高度? – Fenton

+0

[看看这个](http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome) – Malkus

回答

1

我的解决方案

img.clone().load(function() { 
    img.Dwidth = $(this).width(); 
    img.Dheight = $(this).height(); 
}).appendTo(img.parent()).hide(); 

为了让显示器的尺寸,在我的具体情况,我不得不克隆元素,重新加载,并得到了尺寸。

0

您应该使用jQuery widthheight进行计算,并且如果该项目可见,则始终得到0.如果更新下面的代码,它应该可以工作。

$('<img/>').attr('src',img.src).load(function() { 
    img.Owidth = $(this).width(); 
    img.Oheight = $(this).height(); 
}).appendTo($('body')).hide(); 

,你能理解,如果你已经使用$(本).WIDTH()而不是this.width在第二块它应该工作。

+0

不幸的是,事实并非如此,它不起作用。此外,这给了我原始图像尺寸,而不是在容器内显示的图像的尺寸,或者仅具有定义的宽度值。 – Joey

+0

你是什么意思“当它被加载和显示。”。这个函数应该给图像的尺寸,但如果你有另一个显示图像不同宽度或高度的元素(通过attr或CSS),你应该在该对象上使用$()。width()。 –

+0

@Joey请检查这个简单的例子http://jsfiddle.net/bvBKD/ –

0

当您使用$(window).load函数加载脚本时,您将从图像中获得大小。

$(window).load(function(){ 
    console.log($('img').width()); 
}); 
0
var getheight = function() { 
var img = document.getElementById("pic"); 
var img_width = img.clientWidth; 
} 

调用此函数图像被加载后。 clientWidth属性会在加载后为您提供图片大小

相关问题