純 CSS 創作一個小球繞著圓環盤旋的動畫
阿新 • • 發佈:2018-11-24
效果預覽
按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。
https://codepen.io/comehope/pen/gKxyWo
可互動視訊
此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。
請用 chrome, safari, edge 開啟觀看。
https://scrimba.com/p/pEgDAM/cg48mty
原始碼下載
本地下載
每日前端實戰系列的全部原始碼請從 github 下載:
https://github.com/comehope/front-end-daily-challenges
程式碼解讀
定義 dom,容器中包含一個圓環和3個小球:
<div class="container"> <div class="ring"></div> <div class="spheres"> <span class="sphere"></span> <span class="sphere"></span> <span class="sphere"></span> </div> </div>
居中顯示:
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: darkslategray;
}
改變盒模型:
* {
box-sizing: border-box;
}
畫出圓環:
.container { position: relative; font-size: 20px; } .ring { position: relative; width: 10em; height: 10em; border: 1.5em solid paleturquoise; border-radius: 50%; }
在圓環的左上方畫出一個小球:
.sphere {
position: absolute;
top: -20%;
left: -20%;
}
.sphere::after {
content: '';
position: absolute;
width: 3em;
height: 3em;
background-color: lightseagreen;
border-radius: 50%;
}
讓小球在圓環的左上方盤旋:
.sphere {
width: 80%;
height: 80%;
animation: rotate 1.5s linear infinite;
}
@keyframes rotate {
to {
transform: rotate(360deg);
}
}
讓小球的圓環的上下穿梭:
.ring {
z-index: 2;
}
.sphere {
animation:
rotate 1.5s linear infinite,
overlapping 1.5s linear infinite;
}
@keyframes overlapping {
to {
z-index: 2;
}
}
通過設定動畫延時,製造 3 個小球同時盤旋的效果:
.sphere:nth-child(2) {
animation-delay: -0.5s;
}
.sphere:nth-child(3) {
animation-delay: -1s;
}
最後,讓容器轉動起來,製造小球圍繞圓環盤旋的效果:
.container {
animation: rotate 5s linear infinite;
}
大功告成!
原文地址:https://segmentfault.com/a/1190000015295466