2012-04-26 63 views
2

正在尋找一種獲取外部圖像的尺寸(寬度和高度)的方式。
我已經使用prop()attr(),但它們不返回任何值。只是一個錯誤。jQuery:如何獲取外部圖像的尺寸?

例子:

<a href="pathtotheimage">some link</a> 
+2

你唯一的辦法就是裝載圖像。 (如果你使用JavaScript) – 2012-04-26 17:45:26

+0

啊有道理,不能得到尺寸,如果圖像沒有加載。謝謝 – user759235 2012-04-26 20:28:31

回答

9
var imgSrc = "http://server.com/your/image/path/here.jpg" 
var _width, _height; 
$("<img/>").attr("src", imgSrc).load(function() { 
    _width = this.width; 
    _height = this.height; 
}); 
+1

如果圖像從瀏覽器緩存中提取,'.load'事件不會觸發。請參閱[此問題](http://stackoverflow.com/q/3877027/901048)瞭解解決方案。 – Blazemonger 2012-04-26 18:12:51

-1

這不是技術上的jQuery但我會往下走的路線:使用widthheight

var image = new Image(), width, height; 
image.src = 'http://whereyourimage.is/heresmyimage.jpg'; 
width = image.width; 
height = image.height; 

然後,您可以訪問這些值,例如alert('My image is ' + width + ' pixels accross.');

+2

這是行不通的,因爲您在設置src的同時訪問寬度,因此瀏覽器無法提供正確的信息。 – Esailija 2012-04-26 17:55:18

+0

爲我工作,但我剛剛意識到圖像被緩存!傻子!當我回到電腦時將編輯答案 – freshnode 2012-04-26 18:50:38

1

看起來像沒有提供了一個工作香草JS答案。

var img = document.createElement('img') 
img.src = 'http://domain.com/img.png' 
img.onload = function() { 
    console.log(this.width) 
    console.log(this.height) 
} 

這裏是一個的jsfiddle:http://jsfiddle.net/Ralt/VMfVZ/