我正在尝试构建一个预加载器,该预加载器实际上代表已加载内容的“百分比”。不一定是数字,而是使用动画框(从窗口的左到右缩放)。当前,我正在使用此代码来确定页面上有多少图像,并在加载所有图像时构建一个网格。

$(document).ready(function() {
num_images = $("img").length;
img_counter = 0;
$("img").css("display", "none");

$(".grid-item").each(function() {
    $(window).load(function() {
        img_counter++;
        if (img_counter == num_images) {
            console.log(num_images);
            $("img").css("display", "block");
            $('.grid').masonry({
                itemSelector: '.grid-item',
                isAnimated: true
            });
        }
    });
});
});


然后,在window.load上,我有一个预加载器,它添加了“已加载”类。

$('.preloader').addClass('loaded');
setTimeout(function() {
    $('.content').css('opacity', 1);
    $('.preloader').css({'transform': 'translateY(-50px)'});
}, 500);


所有这些都给人一种幻觉,即具有加载功能,但实际上并没有显示“加载”过程。如何确定要加载多少内容并以预加载器的宽度显示?

这是我正在使用的基本测试页。在此先感谢一吨!我不一定需要答案,而是指导或指导。

http://andyrichardson.design/masonry/

最佳答案

为图像添加onload函数,并在pnload函数触发时增加计数器(这意味着已加载图像)

$(document).ready(function() {
num_images = $("img").length;
   img_counter = 0;
  $('img').load(function(){
   img_counter++;
   // do your other stuff here
});
}

10-05 20:29
查看更多