【问题标题】:control height and width client side with javascript用javascript控制客户端的高度和宽度
【发布时间】:2015-05-17 14:50:20
【问题描述】:

这是我的表格

<form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp">
        <input type="file" name="pho" id="photo" class="inph" accept="image/*">
        <button type="submit" id="subFormPhoto" class="spp">press here</button>
</form>

这是我的代码 JS

<script type="text/javascript">
    var inputPhoto= document.getElementById('photo');
    inputPhoto.onchange=function(){var photo= this.value; photo.onload=function(){alert(this.width+' '+this.height);};};
</script>

我的问题是没有可视化alert(this.width+' '+this.height);。 好像没有加载photo

【问题讨论】:

  • id 为“insPhotoAlert”的元素在哪里。你的问题能再清楚一点吗?
  • 对不起,我调整了。
  • 我要查看inputPhoto的宽高

标签: javascript controls


【解决方案1】:

this.value 将文件名作为字符串提供,因此您的photo.onload 函数并不是真正查看照片,而只是查看一些字符串。如果你 alertconsole.log photo 你会明白我的意思。

您不妨考虑使用File API,它适用于 HTML 5 起的现代浏览器。

这是您的代码的一个工作示例:

var inputPhoto = document.getElementById('photo');

inputPhoto.onchange = function() {
  var file = this.files[0];
  var reader = new FileReader();
  var photo  = new Image();

  reader.readAsDataURL(file);
  reader.onload = function(_file) {
    photo.src = _file.target.result;
    photo.onload = function() {
      alert(this.width + ' ' + this.height);
    };
  };
};

【讨论】:

    【解决方案2】:

    我试图根据您的问题创建我所理解的内容 http://jsfiddle.net/qo8ovmhn/

     <input type="file" name="pho" id="photo" class="inph" onchange="myFunction()">
    <img id="view" src=""></img>    
    <p id="demo"></p>
    
    
     <script>
     function myFunction() {
    var x = document.getElementById("photo");
    var file = x.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(_file) {
     var img = document.getElementById("view");
     img.setAttribute("src",_file.target.result);
     var height = img.offsetHeight;
     var width = img.offsetWidth;
     alert(width + " X " + height);
    
     };
      }
    </script>
    

    看看这是不是你要找的。 在选择图像时调用输入的更改事件。图像字节被读取并放入图像标签中。然后从图像组件的高度和宽度中获取图像的尺寸。 您可以通过添加可见性的css样式来隐藏图像:隐藏或不透明度:0 不要给 display:none 因为这将导致 0px 的高度和宽度

    最后,尺寸显示在警报中。

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 2017-09-03
      • 1970-01-01
      • 2012-05-06
      • 2010-10-12
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      相关资源
      最近更新 更多