2015-07-18 49 views
-2

我想要做的是根據圖像大小在圖像周圍放置特定大小的「div」。我有我將要在數組中使用的圖像。我需要獲取數組中圖像的高度和寬度。 在將其添加到頁面之前,我必須具有高度和寬度。如何使用JavaScript獲取存儲在數組中的圖像的url大小?

var images = ['pic1.jpg','pic2.jpg','pic3.jpg']; 

for(i = 0; i < images.length; i++){ 

            //then what do i do here? thanks for your help 

} 
+0

可能重複[?如何獲得圖像尺寸(高度和寬度)使用JavaScript(http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript) – FWDekker

+0

不是重複的,以上是在頁面上獲取圖像的高度和寬度..我需要的高度和之前它是附加到頁面 –

+0

然後它是這個可能的重複:http://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript – FWDekker

回答

2

你可以,也許,這樣做:

var img; 
var images = ['pic1.jpg','pic2.jpg','pic3.jpg']; 
var length = images.length; 
var imagesSizes = []; 
var loadedImages = 0; 
for(i = 0; i < length; i++){ 
    img = new Image(); 
    img.addEventListener("load", function(){ 
    var height = this.height, width = this.width; 
    loadedImages++; 
    imagesSizes[i] = { 
     height: height, 
     width: width 
    } 
    if (loadedImages === length) { 
     allImagesAreLoaded(); 
    } 
    }); 
    img.src = images[i]; 
} 
function allImagesAreLoaded() { 
    console.log(imagesSizes); //You will have all their sizes here and each element will match the image index in the original array 
} 
+0

謝謝!我很感激 –

相關問題