仅在完成加载后才淡入图像

Fade in image only after finish loading

本文关键字:淡入 图像 加载      更新时间:2023-09-26

我在一个页面上有一些图像是随机加载的,它们超过了100kbs,是否可以将其完全加载,然后淡入,而不是逐渐加载?

我的JS是这样的。。。

(function($){   
$.randomImage = {
    defaults: {         
        //you can change these defaults to your own preferences.
        path: '_images/', //change this to the path of your images
        myImages: ['hero_eagle.jpg', 'hero_giraffe.jpg', 'hero_owl.jpg', 'hero_rabbit.jpg']
    }           
}   
$.fn.extend({
        randomImage:function(config) {              
            var config = $.extend({}, $.randomImage.defaults, config);              
             return this.each(function() {                      
                    var imageNames = config.myImages;                       
                    //get size of array, randomize a number from this
                    // use this number as the array index
                    var imageNamesSize = imageNames.length;
                    var lotteryNumber = Math.floor(Math.random()*imageNamesSize);
                    var winnerImage = imageNames[lotteryNumber];
                    var fullPath = config.path + winnerImage;                       
                    //put this image into DOM at class of randomImage
                    // alt tag will be image filename.
                    $(this).attr( { src: fullPath });                                   
            }); 
        }           
}); 
})(jQuery);

应该能够,只需在样式表中将图像设置为display:none,并修改将src设置为以下值的脚本位:

$(this).attr( { src: fullPath }).load(function() {
  $(this).fadeIn()
});  

从使用CSS隐藏的图像开始。然后使用:

 $(document).ready(function() {
   // Code goes here.
 });

并在那里执行淡入。

还有另一个SO问题讨论了使用jQuery预加载图像:使用jQuery 预加载图像

引用顶部答案:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}
// Usage:
preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

如果您希望在淡入之前预加载所有图像,并向用户显示加载消息,则可以使用以下方法:

                var gotime = imgArray.length;
                $(".maxCount").text(gotime);
                var imgCounter = 0;
                $.each(imgArray, function(){
                    $(new Image()).load(function(){
                        imgCounter++;
                        $(".presentCount").text(imgCounter);
                        if (--gotime < 1) {
                            $("#content").fadeIn();
                        }
                    }).attr('src', this);
                });