图片加载失败后的占位图处理

<img />标签,如果因为网络或者跨域限制等原因无法正常加载,会出现图片裂开的样子,如果设置了alt属性值,则alt属性对应的内容也会一并显示。例如:

     

这样的效果是不太好看的

我们可以用一张占位图去替换上面裂开的样式 ,这样更为美观,例如:

      

 

 解决方式:

1 <div>
2     <img src="street.jpg" alt="苹果" /> 
3     <img src="http://10.0.5.205:8602/oss/data/commfile/202401/22e6b589-0132-4c4c-b887-773629f700c.png" alt="橙子" /> // 链接图片不存在
4     <img src="moon-night.jpg" alt="香蕉" /> // 图片地址不对
5 </div>
 1 <style>
 2   div {
 3     display: flex;
 4     align-items: center;
 5   }
 6 
 7   img {
 8     margin: 50px 10px;
 9     width: 158px;
10     height: 188px;
11     display: inline-block;
12     transform: scale(1);
13   }
14 
15   img::before {
16     content: '';
17     position: absolute;
18     left: 0;
19     top: 0;
20     width: 100%;
21     height: 100%;
22     background: #f5f5f5 url("imgFail.png") no-repeat 50% 38% / 40% 30%; // 用来调整图片大小和位置
23     color: transparent;
24   }
25 
26   img::after {
27     content: '加载失败';
28     position: absolute;
29     left: 0;
30     bottom: 0;
31     width: 100%;
32     line-height: 7; // 用来调整字体高度和位置
33     color: #c0c4cc;
34     font-size: 14px;
35     text-align: center;
36     white-space: nowrap;
37     overflow: hidden;
38     text-overflow: ellipsis;
39   }
40 </style>

 

效果如下:

                   

 

 

 

 

posted @ 2024-02-23 14:16  Naynehcs  阅读(194)  评论(0编辑  收藏  举报