DIV CSS 佈局教程網

讓圖片在固定區域內自動縮放的 JavaScript 實作
編輯:關於JavaScript     

在製作相簿、商品展示等版面時,常需要讓圖片在一個固定大小的容器內自動縮放,且不能變形、不能被裁切。本文示範一個能依圖片與容器比例智慧縮放並置中的函式。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> <style type="text/css"> #img{ width:600px; height:400px; position:relative; overflow:hidden; background:#996699;} </style> </head> <body> <div id="img"><img src="dsds.JPG" onload="resize_img(this,600,400)" /></div> </body> </html> <script type="text/javascript"> function resize_img(pic,w,h){ var re_new_size=function(r){ //根據比率重新計算寬度 return {w:pic.width/r,h:pic.height/r}; }; var re_offset=function(n){ //根據新的寬高度返回偏移量 return {off_l:(n.w-w)*0.5,off_t:(n.h-h)*0.5}; }; var re_position=function(o,n){ //重新定位圖片 pic.style.cssText="position:absolute;top:"+-o.off_t+"px;left:"+-o.off_l+"px;width:"+n.w+"px;height:"+n.h+"px;"; }; var execute=function(rate){ var new_size=re_new_size(rate), offset_new=re_offset(new_size); re_position(offset_new,new_size); }; var rate_of_w=pic.width/w, rate_of_h=pic.height/h, rate; if(rate_of_w>=1){ //圖片寬度大於顯示區域寬度 if(rate_of_h>=1){ //且圖片高度大於顯示區域高度 rate=Math.min(rate_of_w,rate_of_h); }else{ //圖片高度小於顯示區域 rate=pic.height/h; } }else{ //圖片寬度小於顯示區域寬度 if(rate_of_h>=1){ //且圖片高度大於顯示區域高度 rate=pic.width/w; }else{ //圖片高度小於顯示區域高度 rate=Math.min(rate_of_w,rate_of_h); } } execute(rate); //執行入口 } </script> 

核心邏輯是先算出圖片寬、高各自相對於容器的比例 rate_of_w 與 rate_of_h,再依兩者是否大於 1(代表超出容器)分四種情況選出合適的縮放比率。接著 re_new_size 依比率算出新尺寸,re_offset 算出置中所需的偏移量,最後 re_position 把圖片定位到容器中央。透過 overflow:hidden 的搭配,無論圖片比例如何,都能在容器內呈現整齊、置中且不變形的效果。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved