让我们使用限定范围的自定义属性和 animation-timing-function 制作一个动画 CSS 加载器
跳转到 CodePen 并创建一个新 pen。
为加载器创建标记。请注意内嵌自定义属性的使用:
<div class="loader" style="--count: 10">
<span style="--index: 0"></span>
<span style="--index: 1"></span>
<span style="--index: 2"></span>
<span style="--index: 3"></span>
<span style="--index: 4"></span>
<span style="--index: 5"></span>
<span style="--index: 6"></span>
<span style="--index: 7"></span>
<span style="--index: 8"></span>
<span style="--index: 9"></span>
</div>
您还可以使用生成器 (Pug) 来配置行数:
- const COUNT = 10
.loader(style=`--count: ${COUNT}`)
- let i = 0
while i < COUNT
span(style=`--index: ${i}`)
- i++
为加载器添加一些样式:
loader {
--size: 10vmin;
height: var(--size);
position: relative;
width: var(--size);
}
使用绝对定位以及 calc 与 transform 的组合来定位线条:
.loader span {
background: grey;
height: 25%;
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%)
rotate(calc(((360 / var(--count)) * var(--index)) * 1deg))
translate(0, -125%);
width: 10%;
}
根据 --index 应用不透明度:
.loader span {
opacity: calc(var(--index) / var(--count));
}
让一切旋转起来!
.loader {
animation: spin 0.75s infinite steps(var(--count));
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
请注意 steps(var(--count)) 的用法,以获得正确的效果 ✨
完成!🎉
更喜欢推文形式?🐦
祝您一切顺利!ʕ •ᴥ•ʔ