前端每日实战:52# 视频演示如何用纯 CSS 创做一个小球绕着圆环盘旋的动画

图片描述

效果预览

按下右侧的“点击预览”按钮能够在当前页面预览,点击连接能够全屏预览。css

https://codepen.io/comehope/pen/gKxyWohtml

可交互视频

此视频是能够交互的,你能够随时暂停视频,编辑视频中的代码。前端

请用 chrome, safari, edge 打开观看。git

https://scrimba.com/p/pEgDAM/cg48mtygithub

源代码下载

每日前端实战系列的所有源代码请从 github 下载:chrome

https://github.com/comehope/front-end-daily-challengesapp

代码解读

定义 dom,容器中包含一个圆环和3个小球:dom

<div class="container">
    <div class="ring"></div>
    <div class="spheres">
        <span class="sphere"></span>
        <span class="sphere"></span>
        <span class="sphere"></span>
    </div>
</div>

居中显示:flex

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;
}

大功告成!

相关文章
相关标签/搜索