图片加载失败处理

This commit is contained in:
朱进禄 2020-10-29 15:03:20 +08:00
parent 643cd5bb8f
commit 7c16433182
3 changed files with 77 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

View File

@ -0,0 +1,77 @@
---
title: 图片加载失败处理
date: 2020-10-28 17:34:36
tags:
- 前端
- css
categories:
- 前端杂烩
---
浏览器在图片加载失败之后,默认会显示一个图裂的图标
并且alt属性也会显示出来
```html
<img src="xxx.png" alt="这里是个提示" />
```
<!-- more -->
是这样的效果
![图裂](/images/前端杂烩/图裂.jpg)
### 图片异常处理
多数时候我们都希望能够美化一下,常规方案是这样的
```html
<img src="xxx.png" alt="这里是个提示" onerror="this.src='break.svg';" />
```
使用占位图片进行兜底处理
这样没有问题但是此时这个替换图片就不会显示出alt的内容了
多数时候这个alt的内容是一个需要传递给用户的提示
### CSS函数attr()
这个函数可以用来获取当前DOM元素的属性但是目前**只能作为伪元素content属性的值**
当然获取DOM元素的任意属性都可以的
```html
<div class="box" abc="这里是文字"></div>
```
```css
.box::after{
content: attr(abc);
}
```
#### 同时显示出alt信息
利用attr函数就可以做点比较酷的效果了
```html
<img src="xxx.png" alt="这里是个提示" style="height:100px; width:150px;"
onerror="this.classList.add('error')" />
```
```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;
}
```
效果
![显示alt内容](/images/前端杂烩/显示alt内容.jpg)