---
title: 图片加载失败处理
date: 2020-10-28 17:34:36
tags:
- 前端
- css
categories:
- 前端杂烩
---
浏览器在图片加载失败之后,默认会显示一个图裂的图标
并且alt属性也会显示出来
```html
```
是这样的效果

### 图片异常处理
多数时候我们都希望能够美化一下,常规方案是这样的
```html
```
使用占位图片进行兜底处理
这样没有问题,但是此时这个替换图片,就不会显示出alt的内容了
多数时候这个alt的内容是一个需要传递给用户的提示
### CSS函数attr()
这个函数可以用来获取当前DOM元素的属性,但是目前**只能作为伪元素content属性的值**
当然获取DOM元素的任意属性都可以的
```html
```
```css
img.error {
display: inline-block;
position: relative;
}
img.error::before {
content: '';
background: #FFF url('break.svg') no-repeat;
background-position: center;
background-size: cover;
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
}
img.error::after {
content: attr(alt);
position: absolute;
background: rgba(0, 0, 0, 0.6);
width: 100%;
bottom: 0;
left: 0;
text-align: center;
color: #FFF;
padding: 5px;
}
```
效果
