2013-11-27 51 views
0

假設圖片的原始高度爲200像素或低於100像素。然後我設置圖片的「最大高度:100px」。我將如何獲得它的顯示高度。我試過$('img')。height()。但它只是返回給我一個0值。如何在javascript中獲取圖片的高度

+1

請發佈您的htmn代碼和js代碼。提前致謝。 – Christos

+0

爲什麼你不試圖獲得最大高度呢? '$('#yourImage')。css('max-height');' – Alvaro

+0

如果圖片的高度低於其最大高度怎麼辦?我不想返回最大高度本身。 – ILikebanana

回答

0

使用window.getComputedStyle(火狐,歌劇,Safari瀏覽器):

例如:

<img style="height:100px;max-height:100px;" src="img.gif" id="test"> 
var img = document.getElementById('test'); 
var height = window.getComputedStyle(img).height; 
console.log(height) 

會輸出100像素

對於IE,你可以使用

var height = img.currentStyle.height; 
0

使用簡單的JavaScript:

var img = document.getElementById('imageid'); // use the id of your image 
var height = img.clientHeight; 
0

你需要$(「IMG」)innerHeight() - 獲取第一個元素的當前計算高度匹配的元素,包括填充物而不是邊界。 。 http://api.jquery.com/innerHeight/

0
$(document).ready(function() { 
$("img").load(function() { 
    alert($(this).height()); // for height 
    alert($(this).width()); // for width 
}); 
}); 
0

請確保您已經在此腳本的上方初始化jQuery,因爲在這種情況下,您似乎試圖使用「$」命令使用jQuery。

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 

將上面的代碼放在文檔的頭部。

在體內

,但圖像

<body> 
    <img src="img.jpg" id="new-image" /> 
</body> 

上面是HTML,圖像具有「新圖像」的一個ID

ID可以使用jQuery通過前添加#來選擇ID

eg 「#new-image」

$(document).ready(function(){ 

    // Retrieves computed image height and stores to variable "imgHeight" 
    var imgHeight = $('#new-image').height(); 

    // Shows current computed/displayed height in development console 
    console.log(imgHeight); 

    // If you don't know how to access the development console 
    // You can also use alert (but you should learn to use the console!) 
    alert(imgHeight); 
} 

確保將上述代碼包裝在腳本標記中。

相關問題