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');
});
4

1 回答 1

5

而不是在使用中运行您的代码$(document).ready(...)

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

这将确保页面的资产已加载,包括图像。

于 2012-09-24T21:43:33.470 回答