代码之家  ›  专栏  ›  技术社区  ›  matt

为什么jquery会为DIV的高度返回空值?

  •  13
  • matt  · 技术社区  · 14 年前
    $(document).ready(function(){
    
      function getDocumentHeight()
      {
         // What's the page height?
         var height = $('#mainbody').height();
         alert(height);
       ...
     getDocumentHeight();  }
    

    jquery不断发出警报 null 为了我的身高 #mainbody 我不明白为什么,至少应该是 500px 左右。

    3 回复  |  直到 7 年前
        1
  •  13
  •   Steven    13 年前

    如果动态加载内容,元素可能还没有高度。尝试将此代码移动到页面的正上方底部,看看是否可以解决问题。

    更新: 尝试将代码放入

    $(window).load(function() {
      var height = $('#mainbody').height();
      alert(height);
    });
    

    在你的外部

    $(document).ready();
    
        2
  •  1
  •   Rick    9 年前

    如果您正在为标记使用模板(例如使用Angular或Ember),请使用脚本标记并从模板调用脚本。

    <script type="text/javascript" src="/js/script.js"></script>
    
        3
  •  0
  •   Getz    10 年前

    延迟100毫秒对我来说很有效。立即停止工作。

    setTimeout(function(){
        var imgWidth = $('#id').width();
        var imgHeight = $('#id').height();
        console.log(imgWidth);
        console.log(imgHeight);
    }, 100);