小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
css3 的 animation 属性为 html 的 css 增加不少乐趣,各式各样的动画效果,让前端的页面更加的丰富多彩,今天就模拟一下音符跳动的效果。
效果图
HTML代码
import React from 'react'
import './index.less';
export default () => {
const array = Array.from(Array(6).keys())
return(
<div className='dance-container'>
<!-- 生成若干个音符 -->
{array.map(ele => <div className={`item item${ele}`}></div>)}
</div>
)
}
css 代码
.dance-container {
position: relative;
bottom: 0;
left: 0;
height: 150px;
width: 200px;
background-color: beige;
.item {
<!-- 设置每个子元素为绝对定位,bottom: 0,保证音符跳动效果是从下往上的 -->
position: absolute;
bottom: 0;
width: 20px;
background: linear-gradient(aqua, pink);
animation-timing-function: linear;
animation-iteration-count: infinite;
}
.item1 {
animation-name: dance1;
left: 0;
animation-duration: .6s;
}
.item2 {
animation-name: dance2;
left: 25px;
animation-duration: .4s;
}
.item3 {
animation-name: dance2;
left: 50px;
animation-duration: .35s;
}
.item4 {
animation-name: dance3;
left: 75px;
animation-duration: .4s;
}
.item5 {
animation-name: dance2;
left: 100px;
animation-duration: .4s;
}
.item6 {
animation-name: dance1;
left: 125px;
animation-duration: .5s;
}
}
@keyframes dance1 {
0% {
height: 10px
}
100% {
height: 80px
}
}
@keyframes dance2 {
0% {
height: 40px
}
100% {
height: 120px
}
}
@keyframes dance3 {
0% {
height: 20px
}
100% {
height: 100px
}
}
关键步骤
本文模拟6个音符的跳动
- 设置每个音符的 css 属性 position: absolute
- 为每个属性设置 bottom: 0,这样可以让它的跳动效果是从下而上的(如果要模拟倒着的音符,可以直接去掉绝对定位,有兴趣可以自己尝试一下,这里就不再展示效果了)
- 设置关键帧动画,修改每个兄弟元素的
height,高度的设置是不等的,一般是中间高,两边低。 - 动画直接使用线性变化即可
animation-timing-function: linear - 动画的循环使用无限循环
animation-iteration-count: infinite - 设置每个兄弟元素的
animation-duration,让相邻的不一样,让它们跳动的速度不一致
结语
如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。
文章如有错误之处,希望在评论区指正🙏🙏。
附: