弹跳的正方形动画
这篇教学会使用 CSS 的旋转、边框圆角和虚拟元素,搭配 CSS 动画的时间控制与方向,制作有趣的弹跳正方形动画效果。
快速导览:
制作正方形和阴影
在画面中放入一个 div,运用 CSS 的虚拟元素制作红色大正方形与阴影,透过旋转和绝对定位的方式将其排列如下图,可按照个人喜好修饰,例如渐层色、边框圆角等。
<!-- HTML 程式碼 -->
<div class="box"></div>
<!-- CSS 程式碼 -->
<style>
.box {
position: relative; /* 讓虛擬元素定位有參考依據 */
width: 150px;
margin: 50px;
}
.box::before, .box::after {
content: "";
position: absolute; /* 虛擬元素使用絕對定位 */
}
/* 大正方形 */
.box::before {
z-index: 2;
top: 0;
left: 25px;
width: 100px;
height: 100px;
background: #f55;
transform: rotate(45deg); /* 順時鐘旋轉 45deg */
border-radius: 5px; /* 四個角落圓角半徑 5px */
}
/* 陰影 */
.box::after {
z-index: 1;
width: 20px;
height: 10px;
top: 140px;
left: 65px;
background: #ccc;
border-radius: 50%; /* 四個角落圓角半徑 50% */
}
</style>
制作弹跳的动画
延伸上方范例,分别替正方形和阴影加入 CSS 动画,为了让正方形有“Q 度”,在动画进度中调整碰到地面时,该圆角的半径会变大,就能产生具有弹性效果的正方形 ( 根据不同的正方型大小,可能需要自行调整刚好碰到地面的位置 ),阴影的动画较为简单,只需要控制阴影位置和大小,当正方形往上时阴影变小,往下时阴影变大。
<!-- HTML 程式碼 -->
<div class="box"></div>
<!-- CSS 程式碼 -->
<style>
.box {
position: relative;
width: 150px;
margin: 50px;
}
.box::before, .box::after {
content: "";
position: absolute;
}
.box::before {
z-index: 2;
top: 0;
left: 25px;
width: 100px;
height: 100px;
background: #f55;
transform: rotate(45deg);
border-radius: 5px;
/* 動畫效果,反覆無限播放、加速度啟動 */
animation: oxxo alternate infinite ease-in 0.4s;
}
.box::after {
z-index: 1;
width: 20px;
height: 10px;
top: 140px;
left: 65px;
background: #ccc;
border-radius: 50%;
/* 動畫效果,反覆無限播放、加速度啟動 */
animation: shadow alternate infinite ease-in 0.4s;
}
@keyframes oxxo {
0% {top: 0;}
60% {border-radius: 5px;} /* 圓角半徑 5px 持續到 60% */
100% {
top:45px;
border-bottom-right-radius: 50px; /* 碰到地面時圓角半徑變成 50% */
}
}
@keyframes shadow {
0% {
left: 65px;
width: 20px;
}
100% {
left: 35px;
width: 80px;
}
}
</style>
制作弹跳和旋转的动画
延伸上述范例,加入“旋转”的转换样式,搭配“多重动画”的做法,就能实现同时旋转和弹跳的动画效果。
<!-- HTML 程式碼 -->
<div class="box"></div>
<!-- CSS 程式碼 -->
<style>
.box {
display: inline-block;
position: relative;
width: 150px;
margin: 50px;
}
.box::before, .box::after {
content: "";
position: absolute;
}
.box::before {
z-index: 2;
top: 0;
left: 25px;
width: 100px;
height: 100px;
background: #f55;
transform: rotate(0);
border-radius: 5px;
/* 多重動畫,旋轉的效果不要前後反覆播放,並且設定為線性移動,時間 0.8 秒 為碰撞的兩倍 */
animation: oxxo alternate infinite ease-in 0.4s,
rotateBox infinite linear 0.8s;
}
.box::after {
z-index: 1;
width: 20px;
height: 10px;
top: 140px;
left: 65px;
background: #ccc;
border-radius: 50%;
animation: shadow alternate infinite ease-in 0.4s;
}
/* 旋轉動畫 */
@keyframes rotateBox {
0% {transform: rotate(0);}
100% {transform: rotate(90deg);}
}
@keyframes oxxo {
0% {top: 0;}
60% {border-radius: 5px;}
100% {
top:45px;
border-bottom-right-radius: 50px;
}
}
@keyframes shadow {
0% {
left: 65px;
width: 20px;
}
100% {
left: 35px;
width: 80px;
}
}
</style>
小结
这是只用 CSS 搭配一个 div 就能完成的小动画,可以运用在各种加载效果或页面小惊喜当中,如果有兴趣还可以将其改良成多个正方形、圆形或三角形的弹跳效果。
微信扫码关注
抖音扫码关注