本文若对你有用,给个免费 Star 和关注,持续输出前端各种稀奇古怪的问题
所实现的效果如图
橡皮筋效果回弹.gif
代码如下,注释齐全, 粘贴即用:
<template>
<view class="bounce" :animation="animationData">
<view class ="box" @touchstart="touchstart" @touchend="touchend" @touchmove="touchmove">
<view v-for="i in 20" :key="i">{{i}}</view>
</view>
</view>
</template>
<script>
/**
* touchstart touchend touchmove 需要拖动哪个盒子, 就在哪个盒子写,
* animationData 需要哪个盒子回弹就在那里写
* animationData 与 touchstart touchend touchmove 可以嵌套,父子,同一个盒子,其他关系请自行尝试
*/
export default {
data() {
return {
pageY: 0,
animationData: {},
touchmoveY: 0
}
},
methods: {
// 定义动画
getAnimation(s, h) {
let animation = uni.createAnimation({ // 定义全局初始化动画
duration: s, // 定义动画持续的时间 ms
timingFunction: 'ease', // 定义动画的进行
})
animation.translateY(h).step(); // 移动距离
this.animationData = animation.export() // 将定义的动画赋值给animationData
},
touchstart(e) {
this.pageY = e.touches[0].pageY
},
touchend(e) {
this.getAnimation(300, 0)
},
touchmove(e) {
let pageY = Math.ceil(e.touches[0].pageY)
let h = pageY - this.pageY; // h移动的距离, 是滑动回弹的距离,除以的数越大,距离越小
if (h < 0&& pageY < this.touchmoveY && pageY >= 200) {
this.getAnimation(300, h/2 + 'px'); // 上拉动画
} else {
this.getAnimation(300, h/3 + 'px'); // 下拉动画
}
this.touchmoveY = pageY // 将点的坐标存储起来用于移动时作比较
}
}
}
</script>
<style scoped>
.bounce { width: 200vh; background-color: skyblue; }
.box { width: 100%; transition: all .4s; }
</style>