【问题标题】:Get div height befor the div content is fully loaded在 div 内容完全加载之前获取 div 高度
【发布时间】:2016-02-25 17:25:55
【问题描述】:

我有一个按钮,当我点击时会执行一个 js 代码。像这样。

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

});

第一次加载页面时会出错,但是在将图像等放入缓存后,它可以正常工作。如何等待内容完全呈现以执行高度计算? 所有这些都没有使用延迟功能,也没有使用插件。有一个类似 $(windows).ready() 的函数。

我正在使用 wordpress,并且使用 jquery load() 它在图像完全渲染之前获取高度,并且高度小于 div 中内容的实际高度。

谢谢。

【问题讨论】:

  • 使用 $(document).ready()
  • 你在$( document ).ready()函数中试过了吗?
  • 是的,我尝试了 :( 但它不起作用
  • 你在使用$(document).load()吗? .ready() 在加载 HTML 文档且 DOM 准备就绪时执行,.load() 在整个页面完全加载时执行,包括所有框架、对象和图像
  • @indubitablee 但是 OP 正在使用 ajax 在 div 中加载内容

标签: javascript jquery html wordpress dom


【解决方案1】:

您可以使用以下 sn-p 检查所有添加的图像是否已加载:

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

});

【讨论】:

    【解决方案2】:

    也许我应该说你有两种方法可以做到这一点..一种我没有测试过,另一种我测试过

    第一个:未经测试的方式.promise().done();

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

    2nd: .load 回调函数中的测试方式循环通过图像并使用Image.error(function() {});检查是否已加载

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

    DEMO

    【讨论】:

    • 抱歉,这不起作用。可能是我做错了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多