首頁 > web前端 > js教程 > 主體

JavaScript等比例縮放圖片

高洛峰
發布: 2016-11-28 11:33:14
原創
1234 人瀏覽過

js等比例縮放圖片,這個功能非常實用,當網頁加載一個尺寸比較大的圖片時,往往會把一個網頁撐的變形,頁面變得很難看,於是我們就想到了用JS去控制超出一定範圍的圖片,以穩定頁面佈局,本程式碼片段就是完成了此功能,而且程式碼非常簡潔,效果很好。

<<a href="http://www.php1.cn/">html</a>>
<head>
<title>等比例缩放图片</title>
<script>
function DrawImage(ImgD,iwidth,iheight){    
    //参数(图片,允许的宽度,允许的高度)    
    var image=new Image();    
    image.src=ImgD.src;    
    if(image.width>0 && image.height>0){    
      if(image.width/image.height>= iwidth/iheight){    
          if(image.width>iwidth){      
              ImgD.width=iwidth;    
              ImgD.height=(image.height*iwidth)/image.width;    
          }else{    
              ImgD.width=image.width;      
              ImgD.height=image.height;    
          }    
      }else{    
          if(image.height>iheight){      
              ImgD.height=iheight;    
              ImgD.width=(image.width*iheight)/image.height;            
          }else{    
              ImgD.width=image.width;      
              ImgD.height=image.height;    
          }    
      }    
    }    
}   
</script>
</head>
<body>
<img src=http://up.2cto.com/2013/0803/20130803034531502.jpg" alt="自动缩放后的效果" width="100" height="100" onload="javascript:DrawImage(this,80,80)" />
</body>
</html>
登入後複製


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!