javascript - 如何等到 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);
}}
解决方案
在一种方式中,您可以在 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] ... }
推荐阅读
- asp.net-mvc - 拒绝访问路径“C:\inetpub\wwwroot\App_Data\TEMP\PluginCache”。亚马逊 AWS 豆茎
- jbpm - 多实例子流程 inputDataItem
- ios - 我们的 iOS 应用程序被删除后我能做什么?
- pdf - JsReport Chrome-pdf 配方横向选项
- sql - 在oracle中将父子行转换为JSON
- php - 在 HEADER 中使用用户令牌验证 API
- python - csv.DictReader 分隔符在带有多个引号的 csv 字段中
- python-3.x - 将数据从数据框的顶部移动到底部(df 的列具有不同的长度索引)
- java - 为什么节点被添加到错误的链表中?
- cassandra - 第三个 Cassandra 节点有不同的负载