2009-10-15 176 views
0

好的,所以我有这个“slideshow.html”包含一堆图片和“index.html”。jquery预加载图像

的index.html

<a href="">click</a> 
<ul></ul> 

slideshow.html

<li><img src="1.jpg" alt="" /></li> 
<li><img src="2.jpg" alt="" /></li> 
<li><img src="3.jpg" alt="" /></li> 

和我有我这样的脚本;

$(document).ready(function(){ 
      $('a').click(function(){ 
      $('ul').append('<li id="preloader"><img src="preLoader.gif" /></li>'); 
        $('ul').load('slideshow.html',function(){ 
          $('#preloader').remove(); 
        }); 
      }); 
}); 

,所以我想在点击追加preloader.gif并调用load方法和图像形成slideshow.html后加载到删除动画。使用我的脚本它赢了;不做的事情,页面加载,但动画是在图像完全加载之前下降:(谢谢

回答

2
$(document).ready(function(){ 
    //anchor click 
$('a').click(function(){ 
    //empty the div 
    $('div').empty(); 
      //perform ajax request 
    $('div').load('toLoad.html',function(){ 
        //hides all loaded images 
     $('div.imageHolder img').hide(); 
        //applies preloader for each image loaded 
     $('div.imageHolder img').each(function(){ 
      //creates new image object 
      var img = new Image(); 
          //the current image src is stored in sursa variable 
      var sursa = $(this).attr('src'); 
          //the current image parent is stored in parent var 
      var parent = $(this).parent(); 
          //the load animation is appended to current image parent 
      parent.append('<img src="blueLoader.gif" alt="loader" />'); 
      //loading image css settings 
      $('img[alt="loader"]').css({'display':'block','margin':'10px auto'}); 
          //this is the key 
      $(img).load(function(){ 
          //after image is loaded 
       parent.append($(this)); 
       $(this).hide().fadeIn(500).css({'width':'200px','height':'80px'}); 
       $(this).siblings().remove(); 
      }).attr('src',sursa); 


     }); 

    }); 
    return false; 
}); 
    }); 
+0

kmunky,感谢您的示例代码,我面临着一个有些类似的问题,发现你的代码是非常有用的,谢谢! – 2009-10-18 03:47:09

0

预加载图像做的不同于这个在jQuery中可以做到这样的事情(未经测试):!

$('<ul><li id="image1"><img id="throbber1" scr="preLoader.gif" /></li></ul>').appendTo('body'); 
var $img = $(new Image()).attr('src', '1.jpg').appendTo('ul li#image1'); 
$img.load(function() { 
    $('#throbber1').hide(); 
});