swiper 组件实现 滑动到最后一个 slide 后,再次滑动触发跳转事件

9 篇文章 0 订阅
1 篇文章 0 订阅

该代码只测试了移动端 其他端原理应该相同

技术栈

  • swiper 6.x
  • vue 2.x
  • ts

思路

借助 swiper 提供的 touch 事件

  1. 当用户按下屏幕时,通过 touchStart 记录起始的位置
  2. 通过 touchMove 不断更新坐标点,并判定是否到达可执行操作的临界点
  3. 用户松手触发 touchEnd 事件,在这里面通过(方向,是否是最后一个,是否到达临界点)这些条件判断是否执行用户代码段

核心代码

  /**
   * 是否到最后一个 slide 了
   */
  isEnd: boolean = false;

  /**
   * 手指开始点击的位置 x 坐标
   */
  touchStartX: number = 0;

  /**
   * 用户手指移动时的 x 坐标,touch-move 事件会不停修改该值
   */
  touchMovingX: number = 0;

  /**
   * 是否到达可跳转的距离
   */
  get isArrive(): boolean {
    return Math.abs(this.touchMovingX - this.touchStartX) > 100;
  }

  mounted() {
    this.$nextTick(this.initSwiper);
  }
  
  initSwiper() {
    new Swiper(this.$refs.miniVideo as HTMLElement, {
      slidesPerView: 'auto',
      on: {
        touchStart: (swiper, event) => {
          this.isEnd = swiper.isEnd;
          this.touchStartX = event.targetTouches[0].pageX;
        },
        touchMove: (_, event) => {
          this.touchMovingX = event.targetTouches[0].pageX;
        },
        touchEnd: (swiper, event) => {
          let touchX = event.changedTouches[0].pageX;
          // 判断用户滑动的方向
          const isLeft = touchX - this.touchStartX < 0;
          if (this.isEnd && isLeft && this.isArrive) {
              this.touchStartX = 0
              this.touchMovingX = 0
              // 执行用户代码段 ...
          }
        }
      }
    });
  }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值