本文實例講述了JS圖片等比例縮放方法。分享給大家供大家參考,具體如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>javascript自動按比例顯示圖片,按比例壓縮圖片顯示</title> <script type="text/javascript"> function AutoResizeImage(maxWidth,maxHeight,objImg){ var img = new Image(); img.src = objImg.src; var hRatio; var wRatio; var Ratio = 1; var w = img.width; var h = img.height; wRatio = maxWidth / w; hRatio = maxHeight / h; if (maxWidth ==0 && maxHeight==0){ Ratio = 1; }else if (maxWidth==0){// if (hRatio<1) Ratio = hRatio; }else if (maxHeight==0){ if (wRatio<1) Ratio = wRatio; }else if (wRatio<1 || hRatio<1){ Ratio = (wRatio<=hRatio?wRatio:hRatio); } if (Ratio<1){ w = w * Ratio; h = h * Ratio; } objImg.height = h; objImg.width = w; } </script> </head> <body> <br /> <img src="1.jpg" border="0" width="0" height="0" onload="AutoResizeImage(100,0,this)" /> width:100px <br /> <br /> <img src="1.jpg" border="0" width="0" height="0" onload="AutoResizeImage(0,100,this)" /> height:100px <br /> <br /> <img src="1.jpg" border="0" width="0" height="0" onload="AutoResizeImage(100,100,this)" /> width:100px height:100px <br /> <br /> <br /> <br /> <br /> <br /> <br /> </body> </html>
更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。