門戶網站往往需要展示大量不同尺寸的圖片,為了版面美觀,需要把它們處理成統一比例。本文示範一個基於 jQuery 的方案:頁面載入後,自動把不合比例的圖片縮放並裁剪填滿,且同時相容「已快取」與「未快取」兩種情況。
整個方案分四步:
<cite> 標籤作為「裁剪容器」,其 CSS 與 img 完全相同,並把內部 img 的 margin、padding 歸零。
/* 公用 */
cite { display:block; overflow:hidden; }
/* 某容器 */
#BigPic img { display:block; padding:2px; width:240px; height:160px; border:1px solid #cccccc; }
#BigPic cite { display:block; padding:2px; width:240px; height:160px; border:1px solid #cccccc; }
#BigPic cite img { display:block; margin:0; padding:0; border:none; }
// 圖片尺寸判斷與處理,用裁剪容器包圍
function cutImgz(obj) {
var image = new Image();
image.src = obj.src;
var $this = $(obj);
var iwidth = $this.width(); // CSS 固定的顯示寬度
var iheight = $this.height(); // CSS 固定的顯示高度
// 原始比例與目標比例不一致時才處理
if (1 * image.width * iheight != 1 * iwidth * image.height) {
if (image.width / image.height >= iwidth / iheight) {
$this.height(iheight + 'px');
$this.width((image.width * iheight) / image.height + 'px');
} else {
$this.width(iwidth + 'px');
$this.height((image.height * iwidth) / image.width + 'px');
}
// 用 cite 裝起來,做出裁剪效果
$this.wrap('<cite />');
}
}
這是最容易忽略的細節:在快取中的圖片會「瞬間」load 完成,若在定義 onload 之前就已經載入好,onload 事件反而不會觸發;而未在快取中的圖片若直接處理,因為還沒載入,Image 物件會把原始尺寸誤判為 0。因此需要用 image.complete 來分流:
$('img').each(function () {
var image = new Image();
image.src = this.src;
if (image.complete) {
// 存在快取中,立即處理
cutImgz(this);
} else {
// 不存在快取中,等 onload 再處理
this.onload = function () {
cutImgz(this);
};
}
});
這個方案的巧思在於用 cite 容器 + overflow:hidden 模擬「裁剪」,讓不同比例的圖片都能整齊填滿固定框,而不失真變形。若你被網站編輯上傳的五花八門尺寸圖片困擾過,這套做法值得一試。