2

有人可以帮助我了解如何从 random.php 页面预加载图像,以便在第一次加载时它会淡入淡出。目前它有一个丑陋的批量回声,因为它们没有预加载,但是一旦页面运行,一旦它完全消失在另一个之后......

//Loop through the images and print them to the page
for (var i=0; i < totalBoxes; i++){
  $.ajax({
    url: "random.php?no=",
    cache: false,
    success: function(html) {
      // following line I originally suggested, but let's make it better...
      //$('#bg').append(html).fadeIn('slow');
      // also note the fine difference between append and appendTo.
      var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
      $('img', $d).hover(function() {
        var largePath = $(this).attr("rel");
        $(this).fadeOut("slow", function() {
          $(this).attr({ src: largePath }).fadeIn("slow");
        });
      });
    }
  });
}
4

2 回答 2

3

前几天我写了一个快速插件,它将获取一组图像 URL 并预加载它们,同时让您指定在每个图像加载后和/或所有图像完成加载后要做什么。

jQuery.extend(jQuery, {
    imagesToLoad: 0,
    loadedImages: [],
    preloadImages: function(){
        var settings = {
            urls : [],
            begin : function(){},
            each : function(){},
            complete : function(){},
            scope: window
        };
        jQuery.extend(settings, arguments[0]);
        var images = [];

        jQuery.imagesToLoad = settings.urls.length;

        settings.begin.call(settings.scope, settings.urls);
        for(var i = 0; i < settings.urls.length; i++){
            images[i] = new Image();
            images[i].onload = function(){
                settings.each.call(settings.scope,this);
                jQuery.loadedImages.push(this);
                if(jQuery.loadedImages.length >= jQuery.imagesToLoad){
                    settings.complete.call(settings.scope,jQuery.loadedImages);
                }
            }
            images[i].src= settings.urls[i];
        }
    }
});

然后,您可以通过执行以下操作在代码中使用它:

$.preloadImages({
    urls: ['path/to/image/1.jpg', 'path/to/image/2.jpg'],
    begin: function(urls){
        console.log("loading images %o", urls);
    },
    each: function(image){
        console.log("finished loading %s", image.src);
    },
    complete: function(images){
        // do whatever after all the images are done loading
    }
});
于 2009-11-04T17:51:37.650 回答
0

Here's a trick that I like: on a page before random.php add at the bottom of the page an img tag which references the image you want to fade in on random.php. Add to the img tag a CSS class which is simply display: none. This will prime the user's browser cache with the image so that when they do go to random.php the image was already downloaded and your fade works as expected. Of course this only works if random.php isn't the site landing page. Another factor is how many images you're talking about and their size.

于 2009-11-04T17:27:04.623 回答