2015-05-17 88 views
0

这是我的形式控制高度和宽度客户端与JavaScript

<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

+0

其中是id为'insPhotoAlert'的元素。你能否对你的问题更清楚些? –

+0

对不起,我调整了。 – thorny84

+0

我想查看inputPhoto的宽度和高度 – thorny84

回答

0

this.value给出文件名字符串,所以你的photo.onload函数并不是真的在看照片,而只是一些字符串。如果你alertconsole.logphoto你会明白我的意思。

您不妨考虑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); 
    }; 
    }; 
}; 
0

我试图创建我的理解从你的问题 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 不要给显示:没有,因为这将导致高度和0像素

宽度最后的尺寸如图警报。

+0

非常感谢你 – thorny84