twitter-bootstrap jquery 高度返回 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19201892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 18:45:18  来源:igfitidea点击:

jquery height returns 0

javascriptjquerycsstwitter-bootstrap

提问by Ram

The height property of jquery always returns 0. I am using it along with Bootstrap. Not sure whether it would be of conflict. I went through several online recommended solutions but did not fix it. Below are the code snippets

jquery 的 height 属性总是返回 0。我将它与 Bootstrap 一起使用。不知道会不会有冲突。我经历了几个在线推荐的解决方案,但没有修复它。下面是代码片段

/*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);

回答by Amadan

class="hidden-sm hidden-md hidden-lg"hints that this might be display: none. In this case, heightis not available. Show it, measure it, then hide it.

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

回答by Tauseef

Try the following instead. window.load is not a good way to deal the document elements.

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

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

In case you have more than one elements with the same class, it will get the first element only.

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

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

or alternatively you can use

或者你可以使用

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