一、动画原理
CSS动画通过对元素的样式属性进行变化以实现动画效果。为了让元素能够反弹起来,我们需要使用CSS中的transform属性以及animation属性。具体而言,我们需要对元素进行位移变换,并且在位移过程中加上弹性效果,也就是利用CSS的cubic-bezier()函数来实现。利用animation属性,我们可以控制动画的播放时长,是否循环播放等。
.bounce { animation: bounce 1s ease-in-out infinite; transform-origin: center bottom; } @keyframes bounce { 0%, 100% { transform: translate(0,0); } 50% { transform: translate(0,-25px); animation-timing-function: cubic-bezier(0.5,1.6,0.4,0.8); } }
二、代码解析
上面的代码片段中,我们首先定义了一个类名为“bounce”的元素,这个元素就是我们需要反弹的目标元素。接下来我们对这个元素定义了animation属性,其中“bounce”是动画的名称,1s表示动画播放时长为1秒,ease-in-out表示动画为缓入缓出,infinite表示循环播放。
为了让元素能够在垂直方向上反弹,我们需要将transform-origin属性设为“center bottom”,使得元素在变换时以底部为基准点。
下面的@keyframes规则定义了动画的过程。由于我们需要让元素在垂直方向上反弹,我们定义了两个transform属性:0%和100%时元素的位移是“translate(0,0)”,也就是不进行位移;50%时元素的位移是“translate(0,-25px)”,也就是在垂直方向上进行向上的位移。同时,我们使用了animation-timing-function属性并给它传入一个cubic-bezier函数,以实现弹性效果。
三、应用示例
下面是一个应用示例,我们可以使用这个代码创建出一个反弹的球:
Bouncing Ball .container {
width: 320px;
height: 480px;
background-color: #212121;
display: flex;
justify-content: center;
align-items: center;
}.ball {
width: 50px;
height: 50px;
background-color: #00bcd4;
border-radius: 50%;
animation: bounce 1s ease-in-out infinite;
transform-origin: center bottom;
}@keyframes bounce {
0%, 100% {
transform: translate(0,0);
}
50% {
transform: translate(0,-25px);
animation-timing-function: cubic-bezier(0.5,1.6,0.4,0.8);
}
}原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/206967.html