javascript - 为什么加载图片的 naturalWidth 会返回之前上传图片的宽度?
问题描述
我已成功显示上传图像的预览。现在我需要知道它的naturalWidth
.
但是,当我访问naturalWidth
我的图像时,它会返回先前上传的图像的宽度。
例如:第一张上传的图片宽度为 100,第二张图片宽度为 200。当我上传第一张图片时,警报值为 0。当我上传第二张图片时,该值为 100。
这是我的代码的一部分。
var reader = new FileReader();
reader.onload = function(e) {
$('#img').css("display", "block").attr('src', e.target.result);
var width = document.querySelector('#img').naturalWidth;
alert(width);
};
reader.readAsDataURL(event.target.files[0]);
解决方案
您必须等待 <img> 已加载,然后才能对其进行任何操作,例如访问其 naturalWidth。
另请注意,您在这里绝对不需要 FileReader,从您的文件创建一个 blob:// URL:
// onchange = evt => {
$('#img')
.css("display", "block")
.attr('src', URL.createObjectURL(e.target.files[0])
.one('load', function(e) => {
const width = this.naturalWidth;
alert(width);
});
推荐阅读
- php - 使用排除将 url 转换为 php 中的数组
- asp.net - ASP.NET/IIS HttpErrors 和拒绝访问响应
- dart - 在 Dart 中,是否可以向上转换泛型函数?
- unit-testing - Groovy MockFor:使用多个模拟时如何避免嵌套闭包?
- quarkus - 在本机编译期间,如何在 Quarkus maven 插件中将参数添加到 GraalVM?
- python - gnuplot replot:“矩阵的扫描大小为零”
- laravel - 使用dompdf在laravel 7上将内容导出为PDF时如何修复unicode utf-8?
- c# - 如何从 Xamarin 表单中的 MpAndroidChart(UltimateXF) 获取单击的项目
- r - R按多组应用加权操作
- salesforce - Apex- 设置选项列表字段选定值