[英]naturalWidth and naturalHeight returns 0 using onload event
I have read countless of answers of this issue and I came up with the following, but it doesn't work either.我已经阅读了无数关于这个问题的答案,我想出了以下内容,但它也不起作用。
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");
To summarise, the problem is the event onload
triggers before the images are loaded (or that is how I understand it).总而言之,问题是在加载图像之前触发事件
onload
(或者这就是我的理解)。
Another things to add:还有一点要补充:
onload
event to window
, and it worked, but it takes a lot of time to resize because it waits for everything to load, making the page appear slower, that's how I came to the conclusion the problem has something to do with the onload
event.onload
事件更改为window
,并且它起作用了,但是调整大小需要很长时间,因为它等待所有内容加载,使页面看起来更慢,这就是我得出问题的结论与onload
事件有关。 EDIT:编辑:
I made a fiddle, easier to look at the problem this way https://jsfiddle.net/whn5cycf/我做了一个小提琴,这样更容易看问题https://jsfiddle.net/whn5cycf/
for some reason the function fires before aplying a src to imgCache
由于某种原因,该函数在将 src 应用于 imgCache 之前触发
Well, the reason is that you are calling the function immedeatly:好吧,原因是您正在立即调用该函数:
imgCache[a].onload = function () {
}(a);
// ^^^ calls the function
You call the function and assign undefined
(the return value of that function) to .onload
.您调用该函数并将
undefined
(该函数的返回值)分配给.onload
。
If you want to use an IIFE to capture the current value of a
, you have to make it return a function and accept a parameter to which the current value of a
is assigned to:如果要使用 IIFE 来捕获
a
的当前值,则必须使其返回一个函数并接受将a
的当前值分配给的参数:
imgCache[a].onload = function (a) {
return function() {
scaleImgs(a);
};
}(a);
Have a look again at JavaScript closure inside loops – simple practical example .再看看循环内的 JavaScript 闭包——简单实用的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.