blog-web/source/_posts/前端杂烩/图片加载失败处理.md

77 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
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)