後台編輯的文章常常貼進原始尺寸的大圖,結果版面被撐破或看不全。CSS 的 max-width 可以處理,但受限於舊瀏覽器與圖片本身帶有 width、height 屬性的情況,用 JS 補一層會更穩。
<div id="article">
<img height="800" width="1280" src="/down/js/images/12498880470.jpg" alt="" />
</div>
<script type="text/javascript">
function ResizeImages() {
var myimg, oldwidth, oldheight;
var maxwidth = 550, maxheight = 880;
var imgs = document.getElementById('article').getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
myimg = imgs[i];
if (myimg.width > myimg.height) { // 橫式圖看寬度
if (myimg.width > maxwidth) {
oldwidth = myimg.width;
myimg.height = myimg.height * (maxwidth / oldwidth);
myimg.width = maxwidth;
}
} else { // 直式圖看高度
if (myimg.height > maxheight) {
oldheight = myimg.height;
myimg.width = myimg.width * (maxheight / oldheight);
myimg.height = maxheight;
}
}
}
}
ResizeImages();
</script>
核心觀念只有一個:先把被動的那一邊乘上縮放比例,再限制主動的那一邊,比例才不會跑掉。若你的容器 id 不叫 article,記得改掉 getElementById 的字串。這裡的判斷是「寬 > 高」看寬、否則看高,對接近正方形的圖會偏向以高為準,實務上可改成「超出哪個上限就縮哪邊」。
function controlImg(ele, w, h) {
var c = ele.getElementsByTagName("img");
for (var i = 0; i < c.length; i++) {
var w0 = c[i].clientWidth, h0 = c[i].clientHeight;
var t1 = w0 / w, t2 = h0 / h; // 各自的放大倍率
if (t1 > 1 || t2 > 1 || w0 >= 600) {
var ratio = (t1 > t2 ? t1 : t2); // 取較大的倍率
c[i].width = Math.floor(w0 / ratio);
c[i].height = Math.floor(h0 / ratio);
if (document.all) { // 舊 IE:包一層連結
c[i].outerHTML = '<a href="' + c[i].src + '" target="_blank"'
+ ' title="在新窗口查看圖片">' + c[i].outerHTML + '</a>';
} else {
c[i].title = "在新窗口打開圖片";
c[i].onclick = function () { window.open(this.src); };
}
}
}
}
ele 是容器,w 與 h 是允許的最大寬高,超過就縮。這版的優點是「兩個上限同時考慮」,取倍率較大者相除,因此不管圖片偏橫或偏直都不會溢出;縮完之後還順手包上連結,讓使用者能點開看原圖,體貼度更高。
#article img { max-width: 100%; height: auto; }
max-width 加 height: auto 已是公認的響應式圖片標準寫法,一行取代上面數十行,且不會造成版面抖動(版面在圖片載入後才重排)。JS 方案在需要「縮完就連原圖連結一起產生」或要支援不認得 max-width 的舊環境時仍有價值,但如果是新專案,請直接用 CSS。