自然宽度和自然高度使用onLoad事件返回0 [英] naturalWidth and naturalHeight returns 0 using onload event

查看:39
本文介绍了自然宽度和自然高度使用onLoad事件返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了无数关于这个问题的答案,我想出了以下答案,但也不起作用。

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/

推荐答案

出于某种原因,该函数在将src应用于imgCache之前触发

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

  imgCache[a].onload = function () {

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

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

如果要使用Live捕获a的当前值,则必须使其返回一个函数并接受a的当前值所赋给的参数:

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

重新查看JavaScript closure inside loops – simple practical example

这篇关于自然宽度和自然高度使用onLoad事件返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆