js等比例縮放圖片,這個功能非常實用,當網頁載入一個尺寸比較大的圖片時,往往會把一個網頁撐的變形,頁面變得很難看,於是我們就想到了用JS去控制超出一定範圍的圖片,以穩定頁面配置,本程式碼片段就是完成了此功能,而且代碼非常簡潔,效果很好。
<html><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://www.bkjia.com/uploads/allimg/131122/1043402N6-0.jpg" alt="自動縮放後的效果" width="100" height="100" onload="javascript:DrawImage(this,80,80)" /></body></html>