自然宽度和自然高度使用onLoad事件返回0

本教程将介绍自然宽度和自然高度使用onLoad事件返回0的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

自然宽度和自然高度使用onLoad事件返回0 教程 第1张

问题描述

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

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的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。