简体   繁体   English

naturalWidth 和 naturalHeight 使用 onload 事件返回 0

[英]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:还有一点要补充:

  • I don't know at first the dimensions of the parent nor the child, because they varied depending of their position on the page.一开始我不知道父母和孩子的尺寸,因为它们根据页面上的位置而有所不同。
  • I don't want to use jQuery.我不想使用 jQuery。
  • I tried with another function, changing the 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.

相关问题 从 onLoad() 返回的 React 合成事件<image>里面的元素<svg>没有 naturalWidth 或 naturalHeight 属性 - React synthetic event returned from onLoad() of <image> element inside <svg> does not have naturalWidth or naturalHeight properties naturalHeight 和 naturalWidth Javascript 的问题 - problem with naturalHeight and naturalWidth Javascript naturalHeight与naturalWidth的比较 - naturalHeight comparison with naturalWidth naturalHeight 和 naturalWidth 属性是新增的还是已弃用? - naturalHeight and naturalWidth property new or deprecated? Random 尝试获取图像的 naturalHeight 和 naturalWidth 失败 - Random fails trying to get the naturalHeight and naturalWidth of an image javascript事件:当图像开始加载时挂钩(已经有自然宽度和自然高度道具但尚未加载自身) - javascript event: hook when image starts loading ( already has naturalWidth & naturalHeight props but haven't loaded itself yet) 为什么无法在javascript / JQuery中获取图像的naturalHeight / naturalWidth? - Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery? iframe 元素在 onload 事件后返回未定义? - iframe element returns undefined after onload event? 在Onload事件上使用Javascript Action - Using Javascript Action on Onload event 使用JavaScript,onload事件在body标签中不起作用 - onload event is not working in body tag using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM