2017-04-07 78 views
2

有誰知道爲什麼高度可能爲零嗎?div元素的高度返回零

$(document).ready(function() { 
 
       alert($("#hello").height()); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="hello" class="browseIMG" src="https://udemy-images.udemy.com/course/750x422/64132_926c_10.jpg" />

+0

它給我422警報... – Roy

+0

我已經把代碼放入代碼片段 - 但具有諷刺意味的是代碼現在可以正常工作。 – Tom

回答

5

這是因爲DOM成功加載後,也你甚至從網絡的圖像加載之前獲取圖像的高度。

可能您必須在圖像加載事件中執行此操作。

$('#hello').load(function() { 
    alert($("#hello").height()); 
}); 
+0

太棒了!謝謝 !!!!! –

+0

@MathiasVerhoeven歡迎您:) –

1

刪除document.ready功能,因爲它實際上是加載之前返回元素的高度。

alert($("#hello").height());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="hello" class="browseIMG" src="https://udemy-images.udemy.com/course/750x422/64132_926c_10.jpg" />

0

,因爲你的元素已經沒有尚未加載,試試這個:

$("#hello").load(function() { 
 
       alert($("#hello").height()); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="hello" class="browseIMG" src="https://udemy-images.udemy.com/course/750x422/64132_926c_10.jpg" />