首页 > 解决方案 > 为什么加载图片的 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]);

标签: javascriptjquery

解决方案


您必须等待 <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);
    });

推荐阅读