简体   繁体   English

使用Javascript和Jquery的Website Loader进度栏图像

[英]Website Loader progress bar image Using Javascript and Jquery

So, I am trying to make a website preloader but rather than using the $(window).load function for the whole website, I want to target specific elements of IDs and classes. 因此,我试图制作一个网站预加载器,而不是使用整个网站的$(window).load函数,而是要定位ID和类的特定元素。

I am able to do something like this: 我可以做这样的事情:

var ImgArray = ["#img1","#img2","#img3"];

            for(var i = 0 ; i < ImgArray.length; i++) {
                var name = ImgArray[i];

                $(name).load(function() {


                  //var nameNew = name;// name is a string, passed by Reference 

                  alert(name);

                  //$(this).show();

                });
            }

$('.loader').fadeOut();

I am fading out the loader when all the three images are loaded ie at the end of the 'for loop'. 当所有三个图像都已加载时,即在“ for循环”的末尾,我正在使加载程序褪色。 But still this code is not working well. 但是,此代码仍然无法正常运行。 The loader is fading before all the three images are loaded. 在加载所有三个图像之前,加载程序正在逐渐消失。 If I try to alert the value of name , it shows #img3 all the time, I don't know why ? 如果我尝试提醒name的值,它始终显示#img3,我不知道为什么? Please help me with my code and how to fade the loader at the end of the loop when all the images in the array are loaded. 请帮我提供我的代码,以及在加载数组中的所有图像时如何在循环结束时使加载器褪色。 ?

The reason why your fade happens before all images are loaded is because the .fadeOut() happens before all .load() callbacks are finished. 淡入淡出发生在加载所有图像之前的原因是因为.fadeOut()发生在所有.load()回调完成之前。 Also which version of jQuery are you using? 您还在使用哪个版本的jQuery? .load() for the onload -event was deprecated in version 1.8. 版本1.8中已弃用onload -event的.load .load() You should use .on('load', handler) instead. 您应该改用.on('load', handler)

I would use Promises to code this. 我将使用Promises对此进行编码。 Checkout https://github.com/kriskowal/q and https://github.com/gre/qimage 检出https://github.com/kriskowal/qhttps://github.com/gre/qimage

And the code would look something like 代码看起来像

Q.all([Qimage(img1Url),Qimage(img2Url),Qimage(img3Url)]).spread(function(img1,img2,img3){
    $('#imageContainer').append(img1);
    $('#imageContainer').append(img2);
    $('#imageContainer').append(img3);
    $('.loader').fadeOut();
},function(error){
    console.error(error);
});

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

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