2012-03-15 85 views
1

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

我是這麼認爲的,因爲元素將被給予事件或某事之後是準備好了,如果你想顯示加載用戶可以通過放置元素後,你想要顯示的是完整的,如果這是你可以使用的圖像IMAGE.complete – viyancs 2012-03-15 12:57:53

回答

3

應該可以,只是圖像設置爲display:none在樣式表和修改將src設置爲的腳本位:

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

+1完美。但是這個特殊的'load()'函數在哪裏被記錄? – flu 2013-02-15 13:56:24

+0

here:http://api.jquery.com/load-event/ – danwellman 2013-02-17 21:50:21

+0

謝謝!請記住,這是** depricated **作爲jQuery 1.8,並使用'$(this).attr({src:fullPath})on('load',function(){$(this).fadeIn() ;});'而是。 – flu 2013-02-18 13:47:24

2

開始使用CSS隱藏圖像。然後使用:

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

,並有淡入執行那裏。

還有另外一個SO問題,討論使用jQuery在這裏預加載圖片:Preloading images with 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' 
]); 
0

如果要將所有圖像預加載befo再衰落,並顯示加載信息給用戶,你可以使用這樣的事情:

   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); 
       }); 
相關問題