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

时间:2018-04-04 20:26:53

标签: javascript angular typescript onload

我想验证上传图片的宽度和高度,如果无效,则返回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的值仍然是真的

1 个答案:

答案 0 :(得分:0)

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

结帐MDN的concurrency model and event loop,了解一般情况下这一切是如何运作的。