按比例縮放圖片大小程式碼例項

admin發表於2017-02-23

如果圖片的尺寸超出了要求的大小,可能導致網頁變形等情況,如果固定尺寸的話,那麼就有可能導致圖片變形,那麼網站也不會達到美觀的效果,下面是一段可能是圖片等比例縮放的程式碼例項供大家參考一下,程式碼來源於網路:

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
<script type="text/javascript"> 
jQuery.fn.LoadImage=function(scaling,width,height,loadpic){ 
  if(loadpic==null)loadpic="../img/loading.gif"; 
  return this.each(function(){ 
    var t=$(this); 
    var src=$(this).attr("src") 
    var img=new Image(); 
    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); 
            }
           else{ 
              t.width(img.width); 
              t.height(img.height); 
            } 
          } 
          else{ 
            if(img.height>height){ 
              t.height(height); 
              t.width((img.width*height)/img.height); 
            }
            else{ 
              t.width(img.width); 
              t.height(img.height); 
            } 
          } 
        } 
      } 
    } 
    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(); 
    }); 
  })
} 
$(window).load(function(){ 
  $('#content img').LoadImage(true, 600,500,'img/loading.gif'); 
}); 
</script> 
</head>
<body>
<div id="content"><img src="img/1.jpg"/></div> 
</body>
</html>

相關文章