簡體   English   中英

在div內容已完全加載之前獲取div高度

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

我有一個按鈕,單擊后執行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中內容的實際高度。

謝謝。

您可以使用以下代碼段檢查是否已加載所有添加的圖像:

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

第二:在.load回調函數中循環測試圖像的方式,並使用Image.error(function() {});檢查是否加載了圖像Image.error(function() {});

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

DEMO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM