简体   繁体   English

naturalHeight 和 naturalWidth Javascript 的问题

[英]problem with naturalHeight and naturalWidth Javascript

I try to sort Images by landscape/portrait format therefor I first select all images on the page with the selectFunction() then I sort them with the function "hochquer" which triggers further actions.我尝试按横向/纵向格式对图像进行排序,因此我首先使用 selectFunction() 选择页面上的所有图像,然后使用触发进一步操作的函数“hochquer”对它们进行排序。

my Problem: One image shows up with a width and height of 0 in console.log() even though it is properly displayed on my page and has a actual width and height.我的问题:一个图像在 console.log() 中显示的宽度和高度为 0,即使它在我的页面上正确显示并且具有实际的宽度和高度。 If I reload the Page for a second time it works perfectly fine and I get a width and height for this Image.如果我第二次重新加载页面,它工作得很好,我会得到这个图像的宽度和高度。

can anyone help me with this?谁能帮我这个?

//Screenshot of the console added
function selectFunction() {
  img = document.querySelectorAll(".img");
  let imgSelector = Array.from(img);

  if (imgSelector % 2 != 0) {
    imgSelector.push("even'er");
  }
  return imgSelector;
}

function hochquer(callback) {
    for (let i = 0; i < selectFunction().length; i++) {
      console.log(selectFunction()[i]);
      let Width = selectFunction()[i].naturalWidth;
      console.log(Width, "w");
      let Height = selectFunction()[i].naturalHeight;
      console.log(Height, "h");
      let Ratio = Width / Height;

      if (Ratio >= 1) {
        //quer
        querFormat.push(selectFunction()[i]);
      } else {
        querFormat.push(undefined);
      }
      if (Ratio < 1) {
        //hoch
        hochFormat.push(selectFunction()[i]);
      } else {
        hochFormat.push(undefined);
      }
    }
    callback();
  }

Update:更新:

  1. Screenshot of the console: [1]: https://i.stack.imgur.com/Jr6P8.png控制台截图:[1]: https : //i.stack.imgur.com/Jr6P8.png

  2. some more code I use which I think addresses what @54ka mentioned我使用的更多代码,我认为解决了@54ka 提到的问题

  function newImg() {
    let createImg = [];
    let imgSrc = [];
    const imgContainer = document.querySelector(".gallery");

    for (let i = 0; i < Gallery.length; i++) {
      createImg.push(new Image());
      imgSrc.push(Pfad + Gallery[i]);
      createImg[i].setAttribute("src", imgSrc[i]);
      createImg[i].setAttribute("class", "Img");
      imgContainer.appendChild(createImg[i]);

      function checkImage(path) {
        return new Promise((resolve) => {
          createImg[i].onload = () => resolve({ path, status: "ok" });
          createImg[i].onerror = () => resolve({ path, status: "error" });
        });
      }
      loadImg = function (...path) {
        return Promise.all(path.map(checkImage));
      };
    }

    loadImg(imgSrc).then(function (result) {
      console.log(result);
      hochquer(sort);
    });
  }
  newImg();

Edit: I have made the following changes basing on your comment below after executing previous code.编辑:在执行之前的代码后,我根据您在下面的评论进行了以下更改。

I'm now adding the event listeners to all images in imgLoadCallback( ) and created a callback function containing code from hochquer( ) function.我现在将事件侦听器添加到 imgLoadCallback() 中的所有图像,并创建了一个包含来自 hochquer() 函数代码的回调函数。 Please try to run this code.请尝试运行此代码。

    const imgLoadCallback = function(){
  for (let i = 0; i < selectFunction().length; i++) {
    console.log(selectFunction()[i]);
    let Width = selectFunction()[i].naturalWidth;
    console.log(Width, 'w');
    let Height = selectFunction()[i].naturalHeight;
    console.log(Height, 'h');
    let Ratio = Width / Height;

    if (Ratio >= 1) {
      //quer
      querFormat.push(selectFunction()[i]);
    } else {
      querFormat.push(undefined);
    }
    if (Ratio < 1) {
      //hoch
      hochFormat.push(selectFunction()[i]);
    } else {
      hochFormat.push(undefined);
    }
  }
}

function selectFunction() {
  img = document.querySelectorAll(".img");
  img.forEach(i => i.addEventListener('load', imgLoadCallback))
  let imgSelector = Array.from(img);

  if (imgSelector % 2 != 0) {
    imgSelector.push("even'er");
  }
  return imgSelector;
}

function hochquer(callback) {
  imgLoadCallback();
  callback();
}

From before edit:从编辑前:

Like @54ka has mentioned in the comments, it is possible that the image does not load immediately, usually stuff like loading images from src etc happen in the WEB API Environment asynchronously while execution , in order to not block the primary execution thread.就像@54ka 在评论中提到的那样,图像可能不会立即加载,通常在 WEB API 环境中会在执行时异步加载图像,例如从 src 加载图像等,以免阻塞主执行线程。 Remainder of your code is synchronous, including console.log( )s that you are performing in order to log the width and height to the console, so those happen pretty much immediately as soon as that particular line of code is reached.您的代码的其余部分是同步的,包括您为了将宽度和高度记录到控制台而执行的 console.log()s,因此一旦到达该特定代码行,这些就会立即发生。

Therefore, what I have done in the below code is basically add an event handler for each of the image tags and only when the image has completed 'load' the below code inside the handler will be executed (this is where we are printing the width and height to console now).因此,我在下面的代码中所做的基本上是为每个图像标签添加一个事件处理程序,只有当图像完成“加载”时,才会执行处理程序中的以下代码(这是我们打印宽度的地方和高度来安慰现在)。 Now, this callback function that I have added will only execute after image loads.现在,我添加的这个回调函数只会在图像加载后执行。 So, with this, it will most likely print the correct width and height to console.因此,有了这个,它很可能会向控制台打印正确的宽度和高度。 But I cannot be sure until we run it at your end because you are calling a callback at the very end.但我不能确定,直到我们在你的最后运行它,因为你在最后调用回调。

It was about a delay in the loading of the picture I fixed it with a new approach by using the onload event and code from the link @54ka provided.这是关于图片加载的延迟,我通过使用 @54ka 提供的链接中的onload事件和代码,用一种新方法修复了它。

comment of @54ka: @54ka 的评论:

The reason is that when you first load, you take a size from a picture that has not yet been loaded.原因是当您第一次加载时,您从尚未加载的图片中获取尺寸。 In the refresh browser, it lays it down and manages to show it before the script passes.在刷新浏览器中,它将它放下并设法在脚本通过之前显示它。 To resolve this issue, add an "onload Event" such as: <body onload="myFunction()"> or try this link: Javascript - execute after all images have loaded要解决此问题,请添加“onload 事件”,例如: <body onload="myFunction()">或尝试此链接: Javascript - 在所有图像加载后执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 naturalHeight与naturalWidth的比较 - naturalHeight comparison with naturalWidth 为什么无法在javascript / JQuery中获取图像的naturalHeight / naturalWidth? - Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery? naturalHeight 和 naturalWidth 属性是新增的还是已弃用? - naturalHeight and naturalWidth property new or deprecated? naturalWidth 和 naturalHeight 使用 onload 事件返回 0 - naturalWidth and naturalHeight returns 0 using onload event 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) 从 onLoad() 返回的 React 合成事件<image>里面的元素<svg>没有 naturalWidth 或 naturalHeight 属性 - React synthetic event returned from onLoad() of <image> element inside <svg> does not have naturalWidth or naturalHeight properties Firefox .naturalHeight属性 - Firefox .naturalHeight property 与 .naturalWidth 相关的 Chrome 错误? - Chrome bug related to .naturalWidth? image naturalWidth返回零 - image naturalWidth return zero
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM