2012-09-24 89 views
3

我有一個絕對的div,父母div。我如何根據絕對div來定義父級的高度,知道我有需要一些時間加載的圖像?頁面完成後的元素高度

CSS:

#parent { 
    overflow:hidden; 
    width:100%; 
} 
.absolute { 
    overflow:hidden; 
    width:100%; 
    height:100%; 
} 

HTML:

<div id="parent" style="height:[HEIGHT OF CHILDREN]"> 
    <div id="absolute1" class="absolute"> 
     [LOTS OF CONTENT WHICH MAKE A VARIABLE HEIGHT, INCLUDING IMAGES WHICH TAKE SOME TIMES TO LOAD HERE] 
    </div> 
    <div id="absolute2" class="absolute"> 
     [LOTS OF CONTENT WHICH MAKE A VARIABLE HEIGHT, INCLUDING IMAGES WHICH TAKE SOME TIMES TO LOAD HERE] 
    </div> 
</div> 
<a href="#absolute1">SAMPLE LINK 1</a> 
<a href="#absolute2">SAMPLE LINK 2</a> 

JS:

jQuery(document).ready(function($) { 
    $('a').bind('click', function(e) { 
     var target = $(this).attr('href'); 

     if($(target).html() !== undefined) { 
      $('#parent').css({ 
       'height': $('#parent').find(target).height(), 
      }) 
     } 

     e.preventDefault(); 
    }); 


    // The problem: height is not correct until image is loaded/in cache 
    $('a[href="#absolute1"]').trigger('click'); 
}); 

回答

5

,而不是運行裏面$(document).ready(...)使用代碼:

$(window).load(function(){ 
    // Your code here 
}); 

這將確保頁面的資源已加載,包括圖像。

+0

忘記了!我已經嘗試了很多時間'$(window).ready(function(){';) –

+0

請注意,** ['.load(handler)'在jQuery 1.8中被棄用並且在jQuery 3.0中被刪除](https:// api.jquery.com/load-event/)**。改用'.on(「load」,handler)'。 – Pang