簡體   English   中英

naturalWidth 和 naturalHeight 使用 onload 事件返回 0

[英]naturalWidth and naturalHeight returns 0 using onload event

我已經閱讀了無數關於這個問題的答案,我想出了以下內容,但它也不起作用。

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

如果要使用 IIFE 來捕獲a的當前值,則必須使其返回一個函數並接受將a的當前值分配給的參數:

imgCache[a].onload = function (a) {
  return function() {
    scaleImgs(a);
  };
}(a);

再看看循環內的 JavaScript 閉包——簡單實用的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM