通過css控制,可以實現加載網絡圖片時,未加載完成的時候顯示本地一張占位圖,加載完成后顯示網絡圖片;
原理:通過在img標簽的after偽元素上添加一張占位圖,並且img都設置為position:relative;after設置position:absolute;img標簽的src為網絡圖片,這樣加載的時候由於網絡圖片沒加載完成,就會顯示本地圖片,下面案例中的js是為了效果明顯而故意延時設置img的src屬性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
img {
position: relative;
}
img::after {
content: "";
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
background: url(iphonex.png ) no-repeat center;
}
</style>
</head>
<body>
<img src="">
</body>
<script>
setTimeout(function() {
document.querySelectorAll("img")[0].src = '//upload-images.jianshu.io/upload_images/7450593-65067eb4cf76d882.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240';
}, 3000);
</script>
</html>
