按比例縮小或者放大到某個尺寸,對於標準瀏覽器(如Firefox),或者最新都IE7瀏覽器,
直接使用max-width,max-height;或者min-width,min-height的CSS屬性即可。如:
| 代碼如下 |
複製代碼 |
img{max-width:100px;max-height:100px;} img{min-width:100px;min-height:100px;}
|
對於IE6及其以下版本的瀏覽器,則可以利用其支援的expression屬性,在css code中嵌入javascript code
來實現圖片的縮放
| 代碼如下 |
複製代碼 |
.thumbImage {max-width: 100px;max-height: 100px;} /* for Firefox & IE7 */ * html .thumbImage { /* for IE6 */ width: expression(this.width > 100 && this.width > this.height ? 100 : auto); height: expression(this.height > 100 ? 100 : auto); } |
改寫一下。
| 代碼如下 |
複製代碼 |
#content img{height: expression(this.width > 600 ? this.height = this.height * 600 / this.width : "auto"); width: expression(this.width > 600 ? "600px" : "auto"); max-width:600px;} |
在IE6、IE7下可以實際大圖片按比例縮小,不會出現圖片變形的情況,在FF和chrome下,expression無效,但通過max-width限制圖片最大寬度,使頁面不會被撐開。
css代碼不可能相容所有瀏覽器,後來找了一個js代碼完美的解決了這些問題
| 代碼如下 |
複製代碼 |
<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> |