在CSS3中,我们可以创建动画,无需借助JavaScript的情况下制作出一些简单的动画效果
在本文中,将手把手教你如何使用CSS动画来实现一个小球的运动
我们先看看写出来的效果
让我们开始吧!
首先我们需要创建一个根元素,用来放置小球。
<div class="root">
<!-- 小球 -->
<div class="ball"></div>
</div>
给容器和小球设置下样式。
.root {
background-color: #34495e;
width: 270px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.root .ball {
width: 50px;
height: 50px;
background: orange;
border-radius: 50%;
position: absolute;
}
接下来,我们创建一个让小球运动起来的动画。
@keyframes ball {
100%{
transform: translateY(-130px);
}
}
把这个动画规则挂载到小球元素上,在ball类中添加。
.ball {
animation-name: ball;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-duration: 1s;
}
可以看到,现在小球已经有了动画效果,但是这样子还不够真实,我们再给他添加一个阴影效果。
<div class="root">
<!-- 小球 -->
<div class="ball"></div>
<!-- 小球阴影 -->
<div class="shadow"></div>
</div>
设置下样式。
.root .shadow {
height: 20px;
width: 100px;
background: gray;
position: absolute;
border-radius: 50%;
bottom: 140px;
}
同样,我们也得创建一个阴影的动画,让它发生缩放的改变,并挂载到元素上。
@keyframes shadow {
100%{
transform: scale(.5);
}
}
.shadow{
animation-name: shadow;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-duration: 1s;
}
搞定了,我们来看看效果!
整体代码
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="root">
<!-- 小球 -->
<div class="ball"></div>
<!-- 小球阴影 -->
<div class="shadow"></div>
</div>
</body>
</html>
CSS
.root {
background-color: #34495e;
width: 270px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.root .ball {
width: 50px;
height: 50px;
background: orange;
position: absolute;
border-radius: 50%;
animation-name: ball;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-duration: 1s;
}
.root .shadow {
height: 20px;
width: 100px;
background: gray;
position: absolute;
border-radius: 50%;
bottom: 140px;
animation-name: shadow;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-duration: 1s;
}
@keyframes ball {
100% {
transform: translateY(-130px);
}
}
@keyframes shadow {
100% {
transform: scale(0.5);
}
}