我想验证上传图片的宽度和高度,如果无效,则返回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的值仍然是真的
答案 0 :(得分:0)
这与代码的执行方式有关。 onload
属性表示图像加载时要执行的功能。这是在之后运行您编写的代码,因此在后者console.log
之后。即使图像已经在本地可用,就像这里的情况一样。
结帐MDN的concurrency model and event loop,了解一般情况下这一切是如何运作的。