naturalWidth和naturalHeight使用onload事件返回0

时间:2015-11-18 16:14:43

标签: javascript javascript-events event-handling

我已经阅读了这个问题的无数答案,我想出了以下内容,但它既不起作用。

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(或者我理解它的方式)。

要添加的另一件事:

  • 我一开始不知道父母和孩子的身材, 因为它们在页面上的位置会有所不同。
  • 我不想使用jQuery。
  • 我尝试了另一个功能,将onload事件更改为 window,它有效,但需要花费大量时间才能调整大小 它等待加载所有内容,使页面显得更慢, 这就是我得出的结论,问题有关 使用onload活动。

提前致谢!

编辑:

我做了一个小提琴,这种方式更容易看问题 https://jsfiddle.net/whn5cycf/

1 个答案:

答案 0 :(得分:0)

  

由于某种原因,该函数在将src应用于imgCache

之前触发

嗯,原因是你正在默认调用这个函数:

  imgCache[a].onload = function () {

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

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

如果要使用IIFE捕获a的当前值,则必须使其返回一个函数并接受当前值a分配给的参数:< / p>

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

再次查看JavaScript closure inside loops – simple practical example