商品列表、相簿牆這類頁面,圖片尺寸往往不受控。若想讓它們乖乖待在固定的框內又不被拉歪,靠等比縮放是最省事的做法。
$(window).bind("load", function() {
// IMAGE RESIZE
$('#product_list img').each(function() {
var maxWidth = 120;
var maxHeight = 120;
var ratio = 0;
var width = $(this).width();
var height = $(this).height();
if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
// IMAGE RESIZE
});
邏輯是兩段式:先判斷寬度是否超過上限,超過就按比例縮;接著再判斷高度,同樣按比例縮。兩步走完,無論原圖是橫是直,都會落在 120×120 的框內且不變形。
要注意這裡綁的是 load 而不是 ready——因為要讀取圖片的真實寬高,必須等圖片載入完成才拿得到,這一點是很多人踩過的坑。如果想省事,也可以直接用 CSS 的 max-width:100%; height:auto; 交給瀏覽器處理。