在Javascript中,如何先执行image.onload函数,然后再继续其余的过程



下面是我执行的代码:

<head>
<script>
function uploadFile() {
console.log('here');
var x = document.getElementById('img');
console.log(x.files);
var _URL = window.URL || window.webkitURL;
var file = x.files.item(0);
var img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = function () {
alert("alert1 : this alert should come before");
alert(this.width + " " + this.height);
}
alert("alert2: this alert should come later");
}
</script>
</head>
<body>
<input type='file' id='img' accept="image/*"/>
<input type='submit' value='Upload' onclick='uploadFile()'/>    
</body>
<html>

我希望警报1显示在警报 2之前。

目前,第一个警报 2 显示在警报 1 之前。

image.onload文档如何说:

当图像时,将在图像元素上调用此事件处理程序 已完成加载

似乎在执行第二个警报之前未加载图像。您可以检查图像是否已加载,然后以您的方式处理它。

这是显示警报 2 秒的唯一方法。因为警报 1 取决于图像加载。

img.onload = function () {
alert("alert1 : this alert should come before");
alert(this.width + " " + this.height);
alert("alert2: this alert should come later");
}

最新更新