首页 > 解决方案 > 如何等到 image.src 在 image.onload 事件函数中设置?

问题描述

在我的浏览器 javascript for new image() object 中,对于 onload 事件,我首先在用户选择图像文件后设置 image.src;然后读取图像对象的大小。

但似乎读取发生在正确设置 src 之前。我碰巧找到了两次调用该函数的修复方法。但是这个解决方案似乎是一个非常糟糕的主意。

请让我知道如何以标准方式修复它。我的环境接受 Typescript。

var imgLoaded=false;
 var file = document.getElementById("fileInput").files[0];
      for(let i=0;i<2;i++){    
          call2(file);
         }
      

   function call2(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = function () {
          if(!imgLoaded){ 
              imgLoaded=true;   img.src=(reader.result).toString();}
         else{
        console.log(img.width);
      }}

标签: javascripttypescriptasynchronousbrowser

解决方案


在一种方式中,您可以在 call2 中替换 file = document.getElementById("fileInput").files[0];file = event.target.files[0] 使用它,您也应该将事件传递给 call2

例如:在 html : 中 <input type="file" onchange="call2(event)" />,然后在 js 中function call2(e){let file = e.target.files[0] ... }


推荐阅读