當圖片尺寸來源不一,直接塞進固定大小的容器往往會變形或溢出。用幾行 jQuery,就能讓每張圖在容器內等比縮放並置中呈現。
關鍵在於比較「容器長寬比」與「圖片長寬比」:哪個比例較寬,就以那一側為基準去推算另一邊,這樣才能填滿容器又不 distortion。
// 頁面載入完成後執行
$(document).ready(resizeImage());
function resizeImage() {
$(".pic a img").each(function () {
// 圖片載入完成後才量得到尺寸
$(this).load(function () {
var imgWidth = $(this).width();
var imgHeight = $(this).height();
var boxWidth = $('.pic').width();
var boxHeight = $('.pic').height();
if ((boxWidth / boxHeight) >= (imgWidth / imgHeight)) {
// 以高度為基準縮放
$(this).width((boxHeight * imgWidth) / imgHeight);
$(this).height(boxHeight);
var margin = (boxWidth - $(this).width()) / 2;
$(this).css("margin-left", margin);
} else {
// 以寬度為基準縮放
$(this).width(boxWidth);
$(this).height((boxWidth * imgHeight) / imgWidth);
var margin = (boxHeight - $(this).height()) / 2;
$(this).css("margin-top", margin);
}
});
});
}
一是 $(document).ready() 裡若直接呼叫 resizeImage(),等於在 DOM 還沒就緒時就先執行函式;正確寫法應傳入函式參照 resizeImage,不加括號。
二是快取中的圖片有可能在綁定 load 之前就已完成載入,導致事件永遠不觸發。實務上可先判斷 this.complete,或改用 .on('load') 搭配手動觸發,避免偶發失效。