2012-03-15 83 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); 
       }); 
相关问题