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

Accessing global variable in img.onload function Typescript

我想验证上传图片的宽度和高度,然后 returns 如果无效则返回 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);

在控制台上它记录 'here' 但最后 valido 的值仍然是 true

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

查看 MDN 的 concurrency model and event loop 了解这一切的总体运作方式。