【发布时间】:2016-02-20 11:33:15
【问题描述】:
我已经阅读了无数关于这个问题的答案,我想出了以下内容,但它也不起作用。
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/
【问题讨论】:
标签: javascript javascript-events event-handling