TailwindCSS 实现动态 Loading
如何利用 Tailwind CSS 一行样式实现多样化的动态 Loading 效果。
效果展示
实现原理
通过 tailwindcss 的 Animation 实用工具,我们可以轻松实现 CSS 动画效果。
首先我们来介绍两个关键className:
animate-pulse
它的效果相当于以下 CSS 样式:
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: .5;
}
}
animate-bounce
它的效果相当于以下 CSS 样式:
animation: bounce 1s infinite;
@keyframes bounce {
0%, 100% {
transform: translateY(-25%);
animation-timing-function: cubic-bezier(0.8, 0, 1, 1);
}
50% {
transform: translateY(0);
animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
}
}
接下来,实现旋转的 Loading 需要使用以下 className:
animate-spin
其效果相当于以下 CSS 样式:
animation: spin 1s linear infinite;
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
题外扩展:如何自定义动画 ?
根据官网说明 ,默认情况下,Tailwind 提供四种不同的示例动画和相应的实用工具。您可以通过编辑配置文件来自定义这些值。
module.exports = {
theme: {
extend: {
+ animation: {
+ 'spin-slow': 'spin 3s linear infinite',
+ }
}
}
}
要添加新的动画 ,请使用主题配置的部分 @keyframes
keyframes
。
module.exports = {
theme: {
extend: {
+ keyframes: {
+ wiggle: {
+ '0%, 100%': { transform: 'rotate(-3deg)' },
+ '50%': { transform: 'rotate(3deg)' },
+ }
+ }
}
}
}
然后,您可以在 theme configuration 的部分中按名称引用这些关键帧:animation
module.exports = {
theme: {
extend: {
+ animation: {
+ wiggle: 'wiggle 1s ease-in-out infinite',
+ }
}
}
}
任意值自定义动画
如果您需要使用没有意义包含在主题中的一次性值,请使用方括号使用任意值动态生成属性。
<div class="animate-[wiggle_1s_ease-in-out_infinite]">
<!-- ... -->
</div>
您可以通过以下组件查看具体效果: