通过css控制,可以实现加载网络图片时,未加载完成的时候显示本地一张占位图,加载完成后显示网络图片;
原理:通过在img标签的after伪元素上添加一张占位图,并且img都设置为position:relative;after设置position:absolute;img标签的src为网络图片,这样加载的时候由于网络图片没加载完成,就会显示本地图片,下面案例中的js是为了效果明显而故意延时设置img的src属性。
Documentimg {
position: relative;
}
img::after {
content: "";
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
background: url(iphonex.png ) no-repeat center;
}
setTimeout(function() {
document.querySelectorAll("img")[0].src = 'http://upload-images.jianshu.io/upload_images/7450593-65067eb4cf76d882.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240';
}, 3000);