普歌-uniapp封装手势滑动屏幕核心代码(向左滑,向右滑)

前言:uniapp官方没有提供左滑右滑的事件,但是像探探app那样左滑右滑是怎样实现的呢,本篇就来说一下怎样封装一个uniapp左滑右滑事件

在这里插入图片描述

核心思路

  1. 给容器绑定两个触屏事件touchstart(用户按下)和touchend(用户离开)
  2. 用户按下屏幕事件
    a.记录用户按下屏幕的时间 Date.now() 时间戳,即返回1970-1-1到现在的毫秒数
    b.记录用户按下屏幕的坐标X和Y
  3. 用户离开屏幕事件
    a.记录用户离开屏幕的时间 Date.now()
    b. 记录用户离开屏幕的坐标 x和y
    c. 根据两个时间 运算,判断用户按下的屏幕时长是否合法
    d. 根据两对坐标判断距离是否合法,判断滑动方向

实现步骤

1. 给容器绑定两个触屏事件
<template>
 <view @touchstart="handleTouchstart" @touchend="handleTouchend"> </view>
</template>

<script>
export default {
 data() {
   return {
   };
 },
 methods: {
   /*用户按下屏幕
     1.记录用户按下屏幕的时间  Date.now() 时间戳 返回 1970-1-1到现在的毫秒数
     2.记录用户按下屏幕的坐标x和y
   */
   handleTouchstart(e) {
  console.log(e);
      },
   handleTouchend(e) {
  console.log(e);
},
 },
};
</script>

<style>
view {
 width: 100%;
 height: 500rpx;
 background-color: aqua;
}
</style>

2.用户按下屏幕事件,记录
<script>
export default {
 data() {
   return {
     //按下的时间
     startTime: 0,
     //按下的坐标
     startX: 0,
     startY: 0,
   };
 },
 methods: {
   /*用户按下屏幕
     1.记录用户按下屏幕的时间  Date.now() 时间戳 返回 1970-1-1到现在的毫秒数
     2.记录用户按下屏幕的坐标x和y
   */
   handleTouchstart(e) {
     //记录用户按下的时间
     this.startTime = Date.now();
     //记录用户按下的坐标
     this.startX = e.changedTouches[0].clientX;
     this.startY = e.changedTouches[0].clientY;

     console.log(this.startX);
     console.log(this.startY);
   },
   handleTouchend(e) {},
 },
};
</script>
3.用户离开屏幕事件

<script>
export default {
 data() {
   return {
     //按下的时间
     startTime: 0,
     //按下的坐标
     startX: 0,
     startY: 0,
   };
 },
 methods: {
   /*用户按下屏幕
     1.记录用户按下屏幕的时间  Date.now() 时间戳 返回 1970-1-1到现在的毫秒数
     2.记录用户按下屏幕的坐标x和y
   */
   handleTouchstart(e) {
     //记录用户按下的时间
     this.startTime = Date.now();
     //记录用户按下的坐标
     this.startX = e.changedTouches[0].clientX;
     this.startY = e.changedTouches[0].clientY;
   },
   handleTouchend(e) {
     const endTime = Date.now();
     const endX = e.changedTouches[0].clientX;
     const endY = e.changedTouches[0].clientY;

     //判断按下的时长
     if (endTime - this.startTime > 2000) {
       return;
     }

     //滑动的方向
     let direction = "";

     //先判断用户滑动的距离  用[绝对值 ] 是否合法  合法:判断滑动的方向
       if (Math.abs(endX - this.startX) > 10&&Math.abs(endY-this.startY)<10) {
       //滑动方向  结束大于

       direction = endX - this.startX > 0 ? "right" : "left";
     } else {
       return;
     }

     console.log(direction);
   },
 },
};
</script>
看看效果吧在这里插入图片描述

最后到这就结束了,学到了就一键三连,谢谢啦~

更多推荐:wantLG的《uni-app使用阿里iconfont多色图标


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wantLG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值