Why does jQuery return null for the height of the div?

后端 未结 3 1621
心在旅途
心在旅途 2020-12-17 17:16
$(document).ready(function(){

  function getDocumentHeight()
  {
     // What\'s the page height?
     var height = $(\'#mainbody\').height();
     alert(height);
          


        
相关标签:
3条回答
  • 2020-12-17 17:33

    With 100ms delay works well for me. Without delay not working.

    setTimeout(function(){
        var imgWidth = $('#id').width();
        var imgHeight = $('#id').height();
        console.log(imgWidth);
        console.log(imgHeight);
    }, 100);
    
    0 讨论(0)
  • 2020-12-17 17:42

    If the content is being loaded dynmically, the elements may not have a height yet. Try moving this code to the bottom of the page, directly above and see if that resolves.

    UPDATE: Try placing your code in

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

    outside of your

    $(document).ready();
    
    0 讨论(0)
  • 2020-12-17 17:50

    If you are using a template for your markup for example with angular or ember use the script tag and call the script from the template.

    <script type="text/javascript" src="/js/script.js"></script>
    
    0 讨论(0)
提交回复
热议问题