實作效果
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsQTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5iN0IDN3MWOkBjZ1QWM1YzMzYzX3UzNxATMwMzLclDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
實作代碼
index.html
<h2>未做錯誤處理</h2>
<div style="font-size: 0">
<img src="./img/image.jpg" alt="" />
<img src="./img/image-1.jpg" alt="" />
</div>
<h2>有錯誤處理</h2>
<div style="margin-top: 20px; font-size: 0; display: flex">
<img class="mo-image" src="./img/image.jpg" alt="标題" />
<img class="mo-image" src="./img/image-1.jpg" alt="标題" />
</div>
img {
width: 300px;
height: 150px;
object-fit: cover;
display: inline-block;
}
.mo-image {
display: inline-block;
/* transform: scale(1); */
position: relative;
}
/* 顯示占位圖檔 */
.mo-image::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #f5f5f5 url(../img/image-error.jpg) no-repeat center / 50% 50%;
color: transparent;
}
/* 顯示alt中的文字 */
.mo-image::after {
content: attr(alt);
position: absolute;
left: 0;
bottom: 0;
width: 100%;
line-height: 2;
background-color: rgba(0, 0, 0, 0.5);
color: white;
font-size: 12px;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}