div 元素的高度 returns 零

Height of div element returns zero

有谁知道为什么这里的高度可以为零?

    $(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" />

这是因为即使在 DOM 加载成功之后,您甚至在从网络加载图像之前就得到了图像的高度。

可能你必须在图像的加载事件中这样做。

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

删除 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" />

因为您的元素尚未加载,试试这个:

    $("#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" />