亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何等到 image.src 在 image.onload 事件函數中設置?

如何等到 image.src 在 image.onload 事件函數中設置?

眼眸繁星 2023-06-15 15:59:34
在我的新 image() 對象的瀏覽器 javascript 中,對于 onload 事件,我首先在用戶選擇圖像文件后設置 image.src ;然后讀取圖像對象的大小。但似乎讀取發生在正確設置 src 之前。我碰巧找到了兩次調用該函數的修復方法。但是這個解決方案似乎是一個非常糟糕的主意。請讓我知道如何以標準方式修復它。我的環境接受打字稿。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);      }}
查看完整描述

3 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

在一種方式中,您可以替換 file = document.getElementById("fileInput").files[0];file = event.target.files[0] 并在 call2 中使用它,您還應該將事件傳遞給 call2

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


查看完整回答
反對 回復 2023-06-15
?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

await (img.src= await (reader.result).toString())

也可以。無需調用控制臺。


查看完整回答
反對 回復 2023-06-15
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

我自己至少找到了一個更好的解決方案。雖然我不知道這是否是一個標準。



 var file = document.getElementById("fileInput").files[0];

          call2(file);

      


    function call2(file) {

      var reader = new FileReader();

      reader.readAsDataURL(file);


      reader.onload =async function () {

         img.src= await (reader.result).toString();

         console.log(await img.width);

      }}


查看完整回答
反對 回復 2023-06-15
  • 3 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號