css:利用伪类处理图片加载失败的样式问题

时间:2022-09-30 12:06:07

实现效果 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>

style.css

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

在线示例:https://mouday.github.io/front-end-demo/image-error/index.html

参考 视频:图片加载出错样式最佳实践