讓我們使用限定範圍的自訂屬性和動畫計時函式製作動畫 CSS 載入器
切換至 CodePen 並建立新的筆。
為載入器建立標記。請注意內嵌自訂屬性的使用:
<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))
可達到適當的效果 ✨
太棒了!🎉
偏好使用 Tweet 表單嗎?🐦
時時刻刻享受精彩時刻! GMT •ᴥ• VP