需求是這樣的:一個 div 裡放一張圖,圖的寬度與 div 相同,但高度不固定,希望只顯示圖片垂直居中的那一段,超出的部分裁掉。
示例:

原圖:

<div style="width: 190px; height: 100px; overflow: hidden;"> <img src="example.jpg" width="190px" style="vertical-align: middle;" onload="this.style.marginTop = (parseInt(this.parentNode.style.height) - this.height)/2 + 'px'; this.style.marginLeft = (parseInt(this.parentNode.style.width) - this.width) / 2 + 'px'" /> </div>
三個要素湊在一起就完成了:
1. 外層 div 給 overflow: hidden,負責把超出視窗的部分裁掉。
2. 圖片寬度設成與 div 相同,高度讓它依比例自動展開,所以一定會高於容器。
3. 在 onload 中讀取真實的 this.height,用 (容器高 - 圖高) / 2 算出負的 marginTop,把圖往上推,讓中間那段剛好落在視窗內。
之所以要放在 onload 而不是直接寫在行內,是因為圖片未載入完成前讀不到正確的尺寸,那時候 height 會是 0,算出來的邊距就全錯了。
如果不在意舊版 IE,這個需求用 CSS 三行就能解決,不必寫 JavaScript:
/* 方法一:背景圖片,天生就是居中裁切 */
.box {
width: 190px;
height: 100px;
background: url(example.jpg) center center no-repeat;
background-size: 190px auto;
}
/* 方法二:img 元素 + 絕對定位置中 */
.box {
position: relative;
width: 190px;
height: 100px;
overflow: hidden;
}
.box img {
position: absolute;
width: 190px;
left: 0;
top: 50%;
transform: translateY(-50%);
}
/* 方法三:object-fit,語意最清楚 */
.box img {
width: 190px;
height: 100px;
object-fit: cover;
object-position: center;
}
其中 object-fit: cover 最貼近這個需求:它會讓圖片等比填滿容器並自動裁切多出的部分,一行就搞定。object-position 則用來指定要保留哪個區域,center 就是垂直與水平都居中。
如果是放在列表中大量套用,建議改用 CSS 方案,能省下每張圖各跑一次的 onload 運算。