2016-09-24 126 views
2

我已經搜索過此內容,但是每次執行代碼時,它會返回24作爲高度和寬度,當我上傳400X400圖片時,將返回24。獲取圖片尺寸(高度和寬度)Js或jquery

$(document).on('change','#tt' , function(){ 
    var img = document.getElementById('tt'); 
    var nheight = img.clientHeight; 
    var nwidth = img.clientWidth; 
    alert(nheight) 
    alert(nwidth) 
}); 
<input type="file" id="tt" name="tt" > 

是任何人都知道我能得到400的身高和400的警告框寬度當我上傳400X400圖像。任何幫助真的很讚賞.....

+1

你試圖讓寬度和輸入的高度不圖像。 – Mohammad

+0

現在得到了..謝謝。 @Mohammad – Aamir

回答

2

Onchange創建Image對象的文件上傳事件,並將上傳的文件對象作爲src附加到圖像obj然後onload事件的圖像對象查找圖像的高度和寬度。

請檢查以下代碼片段以獲得更多理解。

var _URL = window.URL || window.webkitURL; 
 
$(document).on('change','#tt' , function(){  
 
    var file, img; 
 
    if ((file = this.files[0])) { 
 
     img = new Image(); 
 
     img.onload = function() { 
 
      alert("width : "+this.width + " and height : " + this.height); 
 
     }; 
 
     img.src = _URL.createObjectURL(file); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="file" id="tt" name="tt" >

+0

['URL.createObjectURL()'](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)是一種實驗性技術,不支持舊版本的瀏覽器。 – Mohammad

+0

它支持所有最新的瀏覽器。你可以參考https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL –

0
var nheight = img.clientHeight; 
var nwidth = img.clientWidth; 

只會讓你的維度。

參見本 -

嘗試

var x = document.getElementById("myImg").naturalWidth; 

的naturalHeight屬性返回圖像的原始高度,或高度屬性來設置或返回圖像的高度屬性的值

http://www.w3schools.com/jsref/prop_img_naturalwidth.asp

+0

在警告框中顯示「未定義」值。 – Aamir

相關問題