CSS控製圖片等比例縮放

來源:互聯網
上載者:User

按比例縮小或者放大到某個尺寸,對於標準瀏覽器(如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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.