jquery 高度返回 0

jquery height returns 0

本文关键字:返回 高度 jquery      更新时间:2023-09-26

jquery 的 height 属性总是返回 0。我正在与引导一起使用它。不确定是否会有冲突。我浏览了几个在线推荐的解决方案,但没有修复它。以下是代码片段

/*html */
<div class="hidden-sm hidden-md hidden-lg" class="mobNewsEvents">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h3 style="text-align: center;">Events</h3>
<div class="mobEvents"> //need to get the height of this div element
 <ul>
   <li>...</li>
 </ul>
</div>
</div>
</div>
</div>
/*script*/
(function($){
$(window).load(function(){
    var temp = $('.mobEvents').height();
    alert(temp);
});
})(jQuery);

class="hidden-sm hidden-md hidden-lg"暗示这可能是display: none。在这种情况下,height不可用。显示它,测量它,然后隐藏它。

请尝试以下操作。 window.load 不是处理文档元素的好方法。

$(document).ready(function(){
    var temp = $('.mobEvents').height();
    alert(temp);
});

如果您有多个具有相同类的元素,它将仅获取第一个元素。

$(document).ready(function(){
    var temp = $('.mobEvents':First).height();
    alert(temp);
});

或者您可以使用

$(document).ready(function(){
    var temp = $('.mobEvents').attr("height").value();
    alert(temp);
});