2012-03-09 32 views
8

我在頁面上調整大小以適合div,例如400x300。如何在jQuery中獲得圖像的全尺寸(〜4000x3000)? .width()和.height()似乎只返回圖像的當前大小。在javascript/jquery中獲取完整尺寸的圖像

+0

感謝..沒看到。 – emc 2012-03-09 09:39:45

回答

21

的圖像具有包含圖像的實際的,非修飾的寬度和高度naturalWidthnaturalHeight性質,即真正的尺寸圖像,而不是CSS設置它。

一個仍然要等待圖像加載雖然

$('#idOfMyimg').on('load', function() { 
    var height = this.naturalHeight, 
     width = this.naturalWidth; 
}); 

另一種選擇是創建一個新的圖像具有相同的文件作爲源,並從該尺寸,只要它從來沒有添加到DOM,而不是外部的風格會影響它

var img = new Image(); 

img.onload = function() { 
    var height = this.height, 
     width = this.width; 
} 
img.src = $('#idOfMyimg').attr('src'); 

FIDDLE

+0

哇...殺手回答 – emc 2012-03-09 09:53:05

+0

快速和完美的解決方案,不犧牲性能:D – Erick 2014-05-13 12:38:14

1

可以與持有像同一個源文件中的Image對象做到這一點:

var preloader = new Image(); 
preloader.src = 'path/to/my/file.jpg'; 

preloader.onload = function(){ 
var height = preloader.height; 
var width = preloader.width; 
} 
-2

試試這個:

VAR PIC = $( 「IMG」)

//需要在img-element已設置寬度和高度的情況下除去這些內容 pic.removeAttr(「width」); pic.removeAttr(「height」);

var pic_real_width = pic.width(); var pic_real_height = pic.height();

+0

仍然會返回當前尺寸! – emc 2012-03-09 09:43:18

+0

不工作:http://jsfiddle.net/kCN2x/ – m90 2012-03-09 09:44:44

+0

我編輯了我的答案,現在它將工作PLZ檢查你的[jsfiddle.net/kCN2x]鏈接 – Java 2012-03-09 09:50:46

4

您可以克隆圖像,刪除高度和寬度屬性,將其附加到主體並獲取寬度和大小,然後刪除它。

的jsfiddle演示是在這裏:http://jsfiddle.net/58dA2/

代碼是:

$(function() { 
    var img = $('#kitteh'); // image selector 
    var hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body'); 
    $('#height').text(hiddenImg.height()); 
    $('#width').text(hiddenImg.width()); 
    hiddenImg.remove();    
});​ 
+1

道具爲強制性貓圖片:) – emc 2012-03-09 09:48:30

+0

@npc Thx!我甚至不是一個「貓人」,但在羅馬時...... :-) – GregL 2012-03-09 09:49:53

+0

+另一個不同的解決方案:) – fider 2013-06-17 12:02:31