2012-11-16 42 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屬性會在加載後爲您提供圖片大小