naturalWidth 和 naturalHeight returns 0 使用 onload 事件

naturalWidth and naturalHeight returns 0 using onload event

我已经阅读了无数关于这个问题的答案,并且想到了以下内容,但它都不起作用。

function fitToParent(objsParent, tagName) {
    var parent, imgs, imgsCant, a, loadImg;
    //Select images
    parent = document.getElementById(objsParent);
    imgs = parent.getElementsByTagName(tagName);
    imgsCant = imgs.length;

    function scaleImgs(a) {
        "use strict";
        var w, h, ratioI, wP, hP, ratioP, imgsParent;

        //Get image dimensions
        w = imgs[a].naturalWidth;
        h = imgs[a].naturalHeight;
        ratioI = w / h;

        //Get parent dimensions
        imgsParent = imgs[a].parentNode;
        wP = imgsParent.clientWidth;
        hP = imgsParent.clientHeight;
        ratioP = wP / hP;

        //I left this as a test, all this returns 0 and false, and they shouldn't be 
        console.log(w);
        console.log(h);
        console.log(ratioI);
        console.log(imgs[a].complete);

        if (ratioP > ratioI) {
            imgs[a].style.width = "100%";
        } else {
            imgs[a].style.height = "100%";
        }
    }

    //Loop through images and resize them
    var imgCache = [];
    for (a = 0; a < imgsCant; a += 1) {
        imgCache[a] = new Image();
        imgCache[a].onload = function () {
            scaleImgs(a);

            //Another test, this returns empty, for some reason the function fires before aplying a src to imgCache
            console.log(imgCache[a].src);

        }(a);
        imgCache[a].src = imgs[a].getAttribute('src');
    }

}
fitToParent("noticias", "img");

总而言之,问题是事件 onload 在图像加载之前触发(或者我是这么理解的)。

要补充的其他内容:

提前致谢!

编辑:

我做了一个fiddle,这样看问题更方便 https://jsfiddle.net/whn5cycf/

for some reason the function fires before aplying a src to imgCache

嗯,原因是 你正在 立即调用函数:

  imgCache[a].onload = function () {

  }(a);
// ^^^ calls the function

您调用该函数并将 undefined(该函数的 return 值)分配给 .onload

如果你想使用 IIFE 来捕获 a 的当前值,你必须使它 return 成为一个函数并接受一个参数,a 分配给:

imgCache[a].onload = function (a) {
  return function() {
    scaleImgs(a);
  };
}(a);

再看看 JavaScript closure inside loops – simple practical example .