怎样用css控制元素做弧线运动?其实要实现元素做弧线运动的效果并不困难,本文有详细的实现思路及实现过程,感兴趣的朋友可以参考看看,接下来我们一起来学习一下吧。
如何使用CSS控制元素弧线运动
我们都知道,CSS3的新属性transfrom过渡效果可以实现元素位移、旋转、缩放。结合animation属性,就可以实现元素的动画效果。但是如何通过css实现元素实现弧线运动呢:
animation属性中有一个 animation-timing-function 属性,动画的速度函数。而这个属性 使用名为三次贝塞尔(Cubic Bezier)函数的数学函数,来生成速度曲线。
cubic-bezier (x1,y1,x2,y2):(三次贝塞尔函数的具体含义请查阅相关资料):
可以通过这个网站 传送门 去实时调节曲线的取值。而animation-timing-function属性中 已经提供了几个 已经封装好的速度函数:也就是我们常用的 ease、linear、ease-in、ease-out、ease-in-out。
效果实现
首先我们能想到的就是将X轴Y轴的位移动画拆开。但是一个元素的动画同一时间只能执行一个动画(最后申明的)。所以我们可以换位思考,用两个父子元素。给父级元素添加X轴位移动画,给子元素增加Y轴位移动画,具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>元素弧线运动</title>
<style>
.box{
width: 400px;
height: 400px;
border: 2px solid #ff8800;
}
span{
display: block;
width: 40px;
height: 40px;
border: 1px solid #222;
animation: center1 2s ease-in forwards;
}
span:after{
content: '';
display: block;
width: 40px;
height: 40px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
background: greenyellow;
animation: center2 2s ease-out forwards;
}
@keyframes center1 {
to{transform: translateX(360px)}
}
@keyframes center2 {
to{transform: translateY(360px)}
}
</style>
</head>
<body>
<div class="box">
<span></span>
</div>
</body>
</html>
此时我用的是元素的伪类after替代了子元素,效果一样.给span一个给色border可以观察两个元素分别的运动轨迹,以便于观察,动画效果如下:
选择ease-in 的曲线效果,此时我们改变 x1,y1的值(将红色点向右拉)。然后复制此时的cubic-bezier()值。将这个值取代原本span的动画 ease-in 的位置。
选择ease-out 的曲线效果,此时我们改变 x2,y2的值(将蓝色点向右拉)。然后复制此时的cubic-bezier()值。将这个值取代原本span伪类after 的动画 ease-out 的位置。
此时的CSS代码如下:
span{
display: block;
width: 40px;
height: 40px;
border: 1px solid #222;
animation: center1 2s cubic-bezier(.66,.01,1,1) forwards;
}
span:after{
content: '';
display: block;
width: 40px;
height: 40px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
background: greenyellow;
animation: center2 2s cubic-bezier(0,0,.36,1) forwards;
}
大型站长资讯类网站! https://www.86zz.com.cn