如何用JavaScript获取存储在数组中的图像的url大小?

时间:2015-07-18 23:37:04

标签: javascript html css arrays

我要做的是放一个特定尺寸的' div'基于图像大小的图像周围。我有将要在数组中使用的图像。我需要获得数组中图像的高度和宽度。 在将其附加到页面之前,我必须具有高度和宽度。

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

}

1 个答案:

答案 0 :(得分: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
}