图片预先加载 jquery

2010-07-12 17:58:32 by 【6yang】, 132 visits, 收藏 | 返回

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<style type="text/css">
 #picLoading img.loading{ background:#ccc; width:120px; height:120px; border:1px solid #333; margin-right:5px;}
</style>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script>

/*
///来源 http://wwww.css88.com
///参数设置:
scaling     是否等比例自动缩放
width       图片最大高
height      图片最大宽
loadpic     加载中的图片路径
*/
(function($){
 jQuery.fn.LoadImage=function(settings){
   settings = jQuery.extend({
         scaling : true,
   width : 500,
   height : 500,
   loadpic:""
     }, settings);
  return this.each(function(i) {
   $.fn.LoadImage.Showimg( $( this ), settings ); 
     });
  };
 $.fn.LoadImage.Showimg = function($this, settings){
  var src=$this.attr("src");
  var img=new Image();
  img.src=src;
  var autoScaling=function(){
   if (settings.scaling) {
    if (img.width > 0 && img.height > 0) {
     if (img.width / img.height >= settings.width / settings.height) {
      if (img.width > settings.width) {
       $this.width(settings.width);
       $this.height((img.height * settings.width) / img.width);
      }
      else {
       $this.width(img.width);
       $this.height(img.height);
      }
     }
     else {
      if (img.height > settings.height) {
       $this.height(settings.height);
       $this.width((img.width * settings.height) / img.height);
      }
      else {
       $this.width(img.width);
       $this.height(img.height);
      }
     }
    }
   }
  }
  $this.attr("src","");
  var loading=$("<img alt="加载中..." title="图片加载中..." src=""+settings.loadpic+"" />");
  $this.hide();
  $this.after(loading);
  $(img).load(function(){
   autoScaling();
   loading.remove();
   $this.attr("src",this.src);
   $this.show();
   
  });
 }
})(jQuery);

$(function(){
 $("img").LoadImage({scaling : true,
   width : 50,
   height : 50,
   loadpic:"loading.gif"});
});


</script>
<body>
 
 <div id="picLoading">
  <img src="images/pic-post01.jpg"  alt="pic"><img src="images/pic-post02.jpg"><img src="images/pic-post03.jpg"><img src="images/pic-post04.jpg">
 </div>
 
</body>
</html>

分享到:
share

    图片原图

    loading

    loading