今天我们来用原生js实现一个骨架屏的效果,效果如下:
首先思考如何实现
思考实现方式
骨架屏的原理是在数据没加载出来的时候,使用滚动的背景颜色去替代,等到加载完毕后则显示对应内容
那么我们的核心就是实现一个.skeleton
的样式,当这个样式出现的时候,就通过animation
去开启一个背景色无限滚动的动画,数据加载完毕后则将这个类名去除即可
思路还是比较简单的,我们先搭建一个整体结构,将数据都写死看看效果单的,我们先搭建一个整体结构,将数据都写死看看效果e单的,我们先搭建一个整体结构,将数据都写死看看效果单的,我们先搭建一个整体结构,将数据都写死看看效果e先
静态结构
<div class="card"><<img src="https://unsplash.com/photos/EaB4Ml7C7fE/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8MTN8fGNvZGV8ZW58MHx8fHwxNjYwMzQwOTQ4&force=true"alt=""/></header><main><h3>I love coding!</h3><p>Talk is cheap. Show me the code.</p><section class="author"><div class="author-avatar"><img src="https://pixabay.com/get/g9ac59ef391ebfbe7b3303ed0278986a31783bedd580d5e097980ed990d9bf646b5dc44932b18fd633df1813686e4f809.png?attachment=" alt="" /></div><div class="author-info"><!-- 名字 --><strong>Plasticine</strong><!-- 日期 --><small>Aug 13, 2022</small></div></section></main" style="margin: auto" />
</div>
再写一些基础样式
img {height: 100%;width: 100%;object-fit: cover;
}
.card {width: 350px;border-radius: 10px;background-color: white;overflow: hidden;box-shadow: 5px 5px 10px 10px rgba(255, 255, 255, 0.2);
}
.card header {height: 200px;
}
.card main {padding: 30px;
}
.card main h3 {margin: 0;
}
.card main p {color: gray;
}
.author {display: flex;align-items: center;gap: 10px;
}
.author .author-avatar {height: 40px;width: 40px