DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> 關於CSS
DIV 內圖片自適應:max-width 加 expression 的雙軌解法
編輯:關於CSS     

以前的做法主要是靠 JavaScript 來控制圖片尺寸,但用過的人都知道有點繁瑣。另一種思路是在外部容器設 overflow: hidden,問題是這只會把圖片切掉,並不會真正縮放。

關鍵其實只有兩行:max-width 加上一行 expression 的補救。

固定像素適應

<!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=gb2312" />
<title>css2.0 VS ie</title>
<style type="text/css">
<!--
body {
  font-size: 12px;
  text-align: center;
  margin: 0px;
  padding: 0px;
}
#pic {
  margin: 0 auto;
  width: 800px;
  padding: 0;
  border: 1px solid #333;
}
#pic img {
    max-width: 780px;
    width: expression(document.body.clientWidth > 780 ? "780px" : "auto");
    border: 1px dashed #000;
}
-->
</style>
</head>
<body>
<div id="pic">
<img src="/articleimg/2006/03/3297/koreaad_10020.jpg" alt="感謝 blueidea 被我盜鏈圖片!" />
</div>
</body>
</html>

百分比適應

<!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=gb2312" />
<title>css2.0 VS ie</title>
<style type="text/css">
<!--
body {
  font-size: 12px;
  text-align: center;
  margin: 0px;
  padding: 0px;
}
#pic {
  margin: 0 auto;
  width: 800px;
  padding: 0;
  border: 1px solid #333;
}
#pic img {
    max-width: 780px;
    width: expression(document.body.clientWidth > document.getElementById("pic").scrollWidth * 9 / 10 ? "780px" : "auto");
    border: 1px dashed #000;
}
-->
</style>
</head>
<body>
<div id="pic">
<img src="/articleimg/2006/03/3297/koreaad_10020.jpg" alt="感謝 blueidea 被我盜鏈圖片!" />
</div>
</body>
</html>

兩者的差別只在判斷條件:固定像素版直接比對視窗寬度與 780px;百分比版則以容器 scrollWidth 的九成作為門檻,讓圖片永遠為容器留出邊距。max-width 負責標準瀏覽器,expression 則補上當時 IE 的空缺。

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