uniapp 滑动动画
在 uniapp 中实现滑动动画可以通过多种方式完成,以下是一些常见的方法和实现细节:
使用 CSS 过渡和动画
通过 CSS 的 transition 或 animation 属性实现滑动效果。这种方法适合简单的滑动需求。

<template>
<view class="container">
<view class="box" :class="{ 'slide-right': isSliding }" @click="toggleSlide"></view>
</view>
</template>
<script>
export default {
data() {
return {
isSliding: false
}
},
methods: {
toggleSlide() {
this.isSliding = !this.isSliding
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #007AFF;
transition: transform 0.3s ease;
}
.slide-right {
transform: translateX(100px);
}
</style>
使用 uni.animate API
uniapp 提供了 uni.animate API,可以实现更复杂的动画效果。
<template>
<view class="container">
<view ref="box" class="box" @click="startAnimation"></view>
</view>
</template>
<script>
export default {
methods: {
startAnimation() {
const animation = uni.createAnimation({
duration: 1000,
timingFunction: 'ease'
})
animation.translateX(100).step()
this.$refs.box.animation = animation.export()
this.$refs.box.setData({
animation: animation.export()
})
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #007AFF;
}
</style>
使用第三方动画库
可以引入第三方动画库如 animate.css 来快速实现滑动动画。

<template>
<view class="container">
<view class="box animate__animated animate__slideInRight" @click="toggleSlide"></view>
</view>
</template>
<script>
export default {
methods: {
toggleSlide() {
// 通过动态添加或移除类名触发动画
}
}
}
</script>
<style>
@import "/common/animate.css";
.box {
width: 100px;
height: 100px;
background-color: #007AFF;
}
</style>
使用手势库实现滑动交互
结合 @touchstart、@touchmove 和 @touchend 事件,可以实现基于手势的滑动动画。
<template>
<view class="container">
<view
class="box"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${offsetX}px)` }"
></view>
</view>
</template>
<script>
export default {
data() {
return {
startX: 0,
offsetX: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].pageX
},
handleTouchMove(e) {
const moveX = e.touches[0].pageX - this.startX
this.offsetX = moveX
},
handleTouchEnd() {
// 滑动结束后可以添加回弹动画等效果
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #007AFF;
transition: transform 0.3s ease;
}
</style>
结合页面生命周期实现页面切换动画
在页面切换时实现滑动效果,可以通过配置页面过渡动画实现。
// pages.json
{
"pages": [
{
"path": "pages/index/index",
"style": {
"animationType": "slide-in-right",
"animationDuration": 300
}
}
]
}
以上方法可以根据具体需求选择适合的实现方式。CSS 过渡适合简单动画,uni.animate 适合复杂动画,手势库适合交互式滑动,页面切换动画适合路由切换场景。






