通过Css控制,实现加载接口下发或者网络图片时,未加载完成前,先加载本地一张占位图,记载完成显示接口下发的图或者网络图。
实现方式:通过在img标签的after伪元素上添加一张占位图,并且img标签都设置为position:relative; after设置position:absolute;img标签的src为接口下发的图片或者网络图片。
这样src链接没加载完成时,会显示本地图片。
代码示例:
<img className="swiper-single-img" src={singleItem.imgUrl} alt="频道图片" />
.swiper-single-img {
width: 36px;
height: 36px;
position: relative;
}
.swiper-single-img::after {
content: "";
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
background: url('../../assets/default-channle.png') no-repeat center;
background-size: 100%;
}
如果需要验证的话,可以将src设置为空,或者延迟2秒后再给设置值。