簡體   English   中英

僅在完成加載后淡入圖像

[英]Fade in image only after finish loading

我在頁面上有一些圖像是隨機加載的,它們的大小超過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);
                });

暫無
暫無

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

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