【问题标题】:Image width and height is not coming in jQuery图像宽度和高度没有出现在 jQuery 中
【发布时间】:2016-04-14 13:21:20
【问题描述】:

我必须使用 jQuery 获取图像的宽度和高度,但我卡在这里。 这里图像宽度和高度显示未定义,请建议我。 感谢您的任何建议。

下面是代码

$(document).ready(function () {
  $("#file").change(function () {
      var files = this.files[0];
      var reader = new FileReader();
      var img = new Image();
      reader.onload = function (e) {
        img.src = e.target.result;
        var fileSize = Math.round(files.size / 1024);///output is coming.
        alert("File size is " + fileSize + " kb");
        alert("width=" + this.width + " height=" + this.height);//showing undefined
      };
      reader.readAsDataURL(files);
  });
});
<input type="file" class="cropit-image-input hii" id="file" style="display: none;" >

【问题讨论】:

  • 试试$(this).width()$(this).height()
  • @Jason 工作正常,但我检查了宽度和高度值,它不是确切的值。其他图像高度和宽度即将到来。

标签: php jquery file filereader


【解决方案1】:

您可以使用img 代替this

 alert("width=" + img.width + " height=" + img.height); 

$(document).ready(function() {
  $("#file").change(function() {
    var files = this.files[0];
    var reader = new FileReader();
    var img = new Image();
    reader.onload = function(e) {
      img.src = e.target.result;
      var fileSize = Math.round(files.size / 1024); ///output is coming.
      alert("File size is " + fileSize + " kb");
 
      alert("width=" + img.width + " height=" + img.height); //showing undefined

    };
    reader.readAsDataURL(files);

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="cropit-image-input hii" id="file">

【讨论】:

  • @sradha,用 sn-p 更新答案
【解决方案2】:

我检查了我的桌面。

当我将 this.widththis.height 分别更改为 img.widthimg.height 时。它奏效了。

改变

alert("width=" + this.width + " height=" + this.height);//showing undefined

alert("width=" + img.width + " height=" + img.height);//showing undefined

【讨论】:

  • 是的@Nana Partykar
猜你喜欢
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2012-07-15
  • 1970-01-01
相关资源
最近更新 更多