我已经阅读了这个问题的无数答案,我想出了以下内容,但它既不起作用。
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
(或者我理解它的方式)。
要添加的另一件事:
onload
事件更改为
window
,它有效,但需要花费大量时间才能调整大小
它等待加载所有内容,使页面显得更慢,
这就是我得出的结论,问题有关
使用onload
活动。提前致谢!
编辑:
我做了一个小提琴,这种方式更容易看问题 https://jsfiddle.net/whn5cycf/
答案 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。