在 CSS3 中,实现动画主要依靠 @keyframes
规则和 animation
属性。@keyframes
规则用于定义动画过程中的关键帧,而 animation
属性用于将定义好的动画应用到选择的元素上。以下是实现动画的基本步骤:
-
定义关键帧 (
@keyframes
): 使用@keyframes
创建动画名称和关键帧。关键帧描述了动画序列中的样式变化。 -
应用动画: 使用
animation
属性将定义的动画应用到元素上。可以控制动画的持续时间、延迟、迭代次数等。
以下都是小例子,直接运行可看到效果
1、淡入淡出动画
<template>
<view class="content">
<view>
<view class="box"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 定义关键帧 */
@keyframes fadeInOut {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.box{
display: block;
width: 100px;
height: 100px;
background-color: orange;
border-radius: 50%;
/* 应用动画 */
animation-name: fadeInOut; /* 动画名称 */
animation-duration: 3s; /* 动画持续时间 */
animation-iteration-count: infinite; /* 动画迭代次数, infinite 是无限循环*/
animation-direction: alternate; /* 动画方向 */
}
</style>
2.旋转动画
<template>
<view class="content">
<view>
<view class="box"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 定义关键帧 */
@keyframes rotateAnimation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.box{
margin-top: 200px;
width: 100px;
height: 100px;
background-color: orange;
/* 应用动画 */
animation: rotateAnimation 2s linear infinite;
}
</style>
3.弹跳动画
<template>
<view class="content">
<view>
<view class="box"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 定义关键帧 */
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-200px);
}
60% {
transform: translateY(-15px);
}
}
.box{
margin-top: 200px;
width: 100px;
height: 100px;
background-color: orange;
/* 应用动画 */
animation: bounce 2s infinite;
}
</style>
4.颜色渐变动画
<template>
<view class="content">
<view>
<view class="box"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 定义关键帧 */
@keyframes colorChange {
0% {
background-color: orange;
}
50% {
background-color: skyblue;
}
100% {
background-color: lightblue;
}
}
.box{
margin-top: 200px;
width: 100px;
height: 100px;
background-color: orange;
/* 应用动画 */
animation: colorChange 5s infinite;
}
</style>