2016-06-14 34 views
0

這似乎是一個相當基本的問題,但無論我怎麼說,我似乎無法找到任何人爲我解決問題的方法。獲取設置爲「自動」的對象的實際高度

我有我們設置的大小,以適合我的佈局,並保留其長寬比,像這樣的圖像:

img{ 
    width:50%; 
    height:auto; 
} 

因爲我不知道圖像有多高,我要計算另一個元素位置使用圖像的實際高度(通過自動調整大小的尺寸)。

$("img").height(); 

但是,只要將它設置爲auto,就會返回0。 我錯過了什麼?或者我怎麼能找到一個圖像設置爲自動:)的當前高度?

謝謝!

+0

的[獲取DIV的高度,沒有高度的CSS設置(http://stackoverflow.com/questions/9592575/get-可能的複製高度的div與無高度設置在css) – nicael

+0

@nicael看起來不像它,不幸的是:( – user3307017

+1

我不明白什麼是問題?https://jsfiddle.net/ XL2000/fkwpdd67​​/ – Midas

回答

2

在香草的JavaScript:

element.offsetHeight; 

確保您的圖像已經加載得到正確的值。爲此,請使用load事件window而不是DOMContentLoaded事件document(或ready在jQuery中)或preload您的圖像通過JS。

+0

工作正常! :) – user3307017

1

您可能正在使用「document ready」事件,而您應該使用load event。在圖像呈現在瀏覽器中之前,您無法檢索圖像的尺寸。

$(window).load(function() { 
 
    $(window).resize(function() { 
 
     console.log('Height: ' + $('img').height()); 
 
    }).resize(); 
 
});
img { 
 
    width: 50%; 
 
    height: auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<img src="http://lorempixel.com/200/200" height="200" width="200">

+0

不完全是。我正在尋找調整後的高度 - 而不是原來的高度。 – user3307017

+0

@ user3307017是的。這個例子中圖像的原始高度是200px。 – Midas

+0

嘗試以全屏模式打開您的代碼段。儘管它幾乎高2000px,但仍然表示250〜 – user3307017

1

我認爲這將是有益的:

document.defaultView.getComputedStyle(document.querySelector("selector")).height; 

它返回與PX的實際高度的字符串。

+0

這也適用! :) – user3307017

0

我的建議是:

$(function() { 
 

 
    // in jQuery you can use: 
 
    var h = $("img").height(); 
 
    console.log('$("img").height() is: ' + h); 
 
    console.log('$("img").css("height") is: ' + $("img").css("height")); 
 
    
 

 
    // in javascript, with the unit measure: 
 
    // This form corresponds to the second jQuery method 
 
    var elem = document.querySelectorAll('img')[0]; 
 
    var h1 = window.getComputedStyle(elem).height; 
 
    console.log('window.getComputedStyle(elem).height is: ' + h1); 
 
});
img{ 
 
    width:50%; 
 
    height:auto; 
 
}
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
 
<img src="https://www.google.it/logos/doodles/2016/karl-landsteiners-148th-birthday-5693101206142976-res.png">