图片加载失败后CSS样式处理

我们在项目开发中,可能会遇到图片服务器宕机,图片显示异常,页面相当不雅严重影响客户体验。下面记录一下在项目中的解决方案:

在书写HTML页面的时候,给图片添加一个错误类:

<img src="xxx.png" alt="图片显示错误" onerror="this.classList.add('error');">

然后配合css实现同时显示错误图片和alt文字提示:

img.error {
  display: inline-block;
  transform: scale(1);
  content: '';
  color: transparent;
}

// 图片显示错误: 显示缺省图片
img.error::before {
  content: '';
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: #f5f5f5 url(break.svg) no-repeat center / 50% 50%;
}

// 图片显示错误: 显示缺省文字提示,这里attr()可以显示当前标签内的所有属性,支持自定义属性
img.error::after {
  content: attr(alt);
  position: absolute;
  left: 0; bottom: 0;
  width: 100%;
  line-height: 2;
  background-color: rgba(0,0,0,.5);
  color: white;
  font-size: 12px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

这样就可以看到图片报错之后,显示的图片和文字提示。

显示效果如下图第二幅图所示:

注意:这里图片地址和错误显示图片地址尽量不要放在同一服务器,因为如果图片服务器宕机,那么替换图片也显示不出来了。

参考链接:https://www.zhangxinxu.com/wordpress/2020/10/css-style-image-load-fail/

原文地址:https://www.cnblogs.com/cap-rq/p/14462141.html