简体   繁体   English

在div内容已完全加载之前获取div高度

[英]Get div height befor the div content is fully loaded

I've got a button, that when I click executes a js code. 我有一个按钮,单击后执行js代码。 Like this. 像这样。

jQuery( ".button" ).on('click', function(){  
    var page = jQuery(this).attr('data-href');//Get data-href with permalink.
    jQuery('#ajax_div').load(page, 
    function(){ 
        var newHeight = jQuery('#content_loaded').height()+200;
        var el = jQuery('#div_containing_ajax_div_and_content_loaded');
        el.css({'height': newHeight + 'px'});
    });

});

The first time it loads the page works wrong, but after have the images, etc, in cache it works ok. 第一次加载页面时工作不正确,但是在缓存了图像等之后,它可以正常运行。 How can I wait that the content is fully rendered to execute the height calc? 如何等待内容完全渲染以执行高度计算? All of this without use delay functions and with out use a plugin. 所有这些都没有使用延迟功能,并且没有使用插件。 There is a function like $(windows).ready(). 有一个类似$(windows).ready()的函数。

I'm using wordpress, and with jquery load() it gets the height before the image is fully render and the height is less than the real height of the content in the div. 我正在使用wordpress,并使用jquery load()在图像完全渲染之前获取高度,并且该高度小于div中内容的实际高度。

Thanks. 谢谢。

You could check that all images added are loaded using following snippet: 您可以使用以下代码段检查是否已加载所有添加的图像:

jQuery(".button").on('click', function () {
    var page = jQuery(this).attr('data-href'); //Get data-href with permalink.
    jQuery('#ajax_div').load(page, function () {
        var $self = $(this),
            $contentImages = $(this).find('img');
        $contentImages.one('load', function () {
            $(this).addClass('loaded');
            if ($self.find('img.loaded').length === $contentImages.length) {
                var newHeight = jQuery('#content_loaded').height() + 200;
                var el = jQuery('#div_containing_ajax_div_and_content_loaded');
                el.css({
                    'height': newHeight + 'px'
                });
            }
        }).each(function () {
            if (this.complete) $(this).triggerHandler('load');
        });
    });

});

maybe I should say that you have 2 ways to do that .. one I'm not tested it and another I tested it 也许我应该说,您有2种方法可以做到这一点..一种是我没有测试过,另一种是我测试过

1st: untested way .promise().done(); 第一:未经测试的方式.promise().done();

jQuery('#ajax_div').load(page).promise().done(function(){
    // var newHeight ......
});

2nd: tested way in .load callback function loop through images and check if loaded or not using Image.error(function() {}); 第二:在.load回调函数中循环测试图像的方式,并使用Image.error(function() {});检查是否加载了图像Image.error(function() {});

$('img').each(function(){
        var Image = $(this);
        var GetSrc = $(this).attr('src');
        Image.error(function() {
            // newHeight ......
        });
 });

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM