如何用純 CSS 創作一個充電 loader 特效
效果預覽
按下右側的“點選預覽”按鈕在當前頁面預覽,點選連結全屏預覽。
https://codepen.io/zhang-ou/pen/deNqdV
可互動視訊教程
此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。
請用 chrome, safari, edge 開啟觀看。
原始碼下載
本地下載
請從 github 下載。
https://github.com/comehope/front-end-daily-challenges/tree/master/008-charging-loader-animation
程式碼解讀
定義 dom,只有一個容器元素:
<div class="battery"></div>
居中顯示:
html, body {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(to bottom, teal, aqua);
}
畫出電池的主體輪廓:
.battery { width: 6em; height: 3em; color: midnightblue; border: 0.5em solid currentColor; border-radius: 0.2em; font-size: 2em; }
畫出電池的突起:
.battery {
position: relative;
}
.battery::after {
content: '';
position: absolute;
width: 0.5em;
height: 2em;
background-color: currentColor;
top: 0.5em;
right: -1em;
border-radius: 0 0.2em 0.2em 0;
}
畫出充電電量:
.battery { background-image: linear-gradient(to right, whitesmoke, whitesmoke); background-repeat: no-repeat; background-size: 30% 80%; background-position: 0.3em 50%; }
定義和應用動畫效果:
@keyframes charge {
from {
background-size: 10% 80%;
}
to {
background-size: 95% 80%;
}
}
.battery {
animation: charge 5s linear infinite;
}
最後,把動畫的時間函式由線性變化改為步長變化:
.battery {
animation: charge 5s steps(8) infinite;
}
大功告成!
知識點
linear-gradient() https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
background-size https://developer.mozilla.org/en-US/docs/Web/CSS/background-size
background-position https://developer.mozilla.org/en-US/docs/Web/CSS/background-position
steps() https://developer.mozilla.org/en-US/docs/Web/CSS/single-transition-timing-function#Timing_functions
currentColor https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Values
border-radius https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius
原文地址:https://segmentfault.com/a/1190000014669547