在img.onload函数Typescript中访问全局变量

问题描述 投票:0回答:1

我想验证上传图像的宽度和高度,如果无效则返回false

我有这个

  let valido = true;
  const img = new Image();
  img.src = window.URL.createObjectURL(event.target.files[0]);
  img.onload = function () {
    const width = img.naturalWidth;
    const height = img.naturalHeight;
    window.URL.revokeObjectURL(img.src);
    // console.log(width)
    // console.log(height)
    if (width > 588 || height > 204) {
      valido = false;
      console.log('here')
    }
  };
  console.log(valido);

在控制台上它会在这里记录,但最后valido的值仍然是真的

javascript angular typescript onload
1个回答
0
投票

这与代码的执行方式有关。 onload属性表示图像加载时要执行的功能。这是在您编写的代码运行之后,因此在后者console.log之后。即使图像已经在本地可用,就像这里的情况一样。

结帐MDN的concurrency model and event loop,了解这一切的一般情况。

© www.soinside.com 2019 - 2024. All rights reserved.