門戶類網站常包含大量不同尺寸的圖片。為保持頁面美觀,通常要求圖片按固定比例顯示。然而編輯人員上傳的圖片尺寸往往不統一,若直接用 CSS 強制拉伸會導致變形。本文提供一套基於 jQuery 的解決方案:頁面加載後自動判斷圖片原始尺寸與顯示區域比例,按比例縮放並居中裁剪,同時完美處理圖片已緩存與未緩存兩種情況。
/* 通用裁剪容器樣式 */
cite {
display: block;
overflow: hidden;
overflow: hidden !important; /* 強制覆蓋 */
}
/* 具體圖片容器樣式(示例) */
#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;
}
/**
* 圖片尺寸判斷與裁剪處理
* @param {HTMLImageElement} obj - 目標圖片 DOM 元素
*/
function cutImgz(obj) {
var image = new Image();
image.src = obj.src;
var $this = $(obj);
// 獲取 CSS 定義的顯示寬高
var iwidth = $this.width();
var iheight = $this.height();
// 若原始比例與顯示比例不一致,則進行處理
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('');
}
}
$(function() {
$('img').each(function() {
var image = new Image();
image.src = this.src;
if (image.complete) {
// 圖片已在緩存中,立即處理
cutImgz(this);
} else {
// 圖片未緩存,等待 onload 觸發
this.onload = function() {
cutImgz(this);
};
}
});
});
單純為了避免與常規佈局標籤衝突,`` 語義上表示引用/標題,樣式重置後作為無語義的裁剪容器極合適。實際項目中可改用 `` 或 `擴展建議