天天看點

css:利用僞類處理圖檔加載失敗的樣式問題

實作效果

css:利用僞類處理圖檔加載失敗的樣式問題

實作代碼

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;
}