jQuery實現的圖片預載入程式碼例項

螞蟻小編發表於2017-02-26
下面是一段圖片預載入程式碼例項,現在很多圖片站都有大量的應用,當然它的好處是很明顯的,下面是一段來自於網路上的程式碼例項和大家分享一下,希望能夠給需要的朋友帶來一定的幫助。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
/* 
* Image preload and auto zoom 
* scaling 是否等比例自動縮放 
* width 圖片最大高 
* height 圖片最大寬 
* loadpic 載入中的圖片路徑 
* example $("*").LoadImage(true,w,h); 
*/
jQuery.fn.LoadImage=function(scaling,width,height,loadpic){ 
  if(loadpic==null)loadpic="../images/loading.gif"; 
    return this.each(function(){ 
      var t=$(this); 
      var src=$(this).attr("src") 
      var img=new Image(); 
      //alert("Loading...") 
      img.src=src; 
      //自動縮放圖片 
      var autoScaling=function(){ 
        if(scaling){ 
          if(img.width>0 && img.height>0){ 
            if(img.width/img.height>=width/height){ 
              if(img.width>width){ 
                t.width(width); 
                t.height((img.height*width)/img.width); 
                t.css("margin-top", (height-t.height())/2); 
              }
              else{ 
                t.width(img.width); 
                t.height(img.height); 
                t.css("margin-top", (height-t.height())/2); 
              } 
            } 
            else{ 
              if(img.height>height){ 
                t.height(height); 
                t.width((img.width*height)/img.height); 
                t.css("margin-top", (height-t.height())/2); 
              }
             else{ 
                t.width(img.width); 
                t.height(img.height); 
                t.css("margin-top", (height-t.height())/2); 
              } 
            } 
          } 
        } 
      } 
      //處理ff下會自動讀取快取圖片 
      if(img.complete){ 
        autoScaling(); 
        return; 
      } 
      $(this).attr("src",""); 
      var loading=$("<img alt=\"載入中...\" title=\"圖片載入中...\" src=\""+loadpic+"\" />"); 
      t.hide(); 
      t.after(loading); 
      $(img).load(function(){ 
      autoScaling(); 
      loading.remove(); 
      t.attr("src",this.src); 
      t.show(); 
    }); 
  }); 
}

相關文章