如何在一個固定大小的 div 中放置圖片,做到「圖片較小時顯示原始大小,超過容器時自動縮放」?這是排版上很實用的技巧。本文示範主要的實作程式碼。
.divImg{
max-height:200px; max-width:200px;
width: expression(this.width > 200 && this.width > this.height ? 200 : auto);
height: expression(this.height > 200 ? 200 : auto);
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html:charset=utf-8"/>
<title>實現圖片加載自適應</title>
<script type="text/javascript" src="../jquery.min.js"> </script>
<script type="text/javascript">
function clickMe(){
var url="../Images/1.jpg";
$("#img").attr("src",url);
$("#img").addClass("divImg");
}
</script>
<style type="text/css">
.divClass {
border: 1px solid red;
width: 200px;
height: 200px;
}
.divImg{
max-height:200px; max-width:200px;
width: expression(this.width > 200 && this.width > this.height ? 200 : auto);
height: expression(this.height > 200 ? 200 : auto);
}
</style>
</head>
<body>
<div class="divClass">
<img id="img" > </img>
</div>
<div>
<input type="button" id="btn" style="width:50px;height: 30px;border:1px solid blue;" value="btn" onclick="clickMe()"/>
</div>
</body>
</html>
關鍵在於透過 max-height、max-width 限制圖片的最大尺寸,再搭配 expression 動態判斷圖片的實際寬高:當圖片寬或高超過 200px 時,就把它限制為 200px,否則保持原始尺寸(auto)。點擊按鈕時,透過 jQuery 動態設定 src 並套用 divImg 樣式,即可完成圖片的自適應顯示。