You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swiper JS:为垂直轮播添加双指滑动功能

为垂直Swiper实现双指滑动功能的方案

方案1:监听原生触摸事件

绕过Swiper自带的touches对象,直接在Swiper容器上监听原生触摸事件,通过TouchList.length判断手指数量:

const swiperContainer = document.querySelector('.swiper-container');
let isTwoFingerTouch = false;

swiperContainer.addEventListener('touchstart', (e) => {
  isTwoFingerTouch = e.touches.length === 2;
});

swiperContainer.addEventListener('touchmove', (e) => {
  if (isTwoFingerTouch) {
    // 自定义双指滑动逻辑,示例:通过双指相对位置判断滑动方向
    const deltaY = e.touches[0].clientY - e.touches[1].clientY;
    if (deltaY < -50) { // 双指向上拉开的阈值
      mySwiper.slideNext();
    } else if (deltaY > 50) { // 双指向下并拢的阈值
      mySwiper.slidePrev();
    }
  }
});

swiperContainer.addEventListener('touchend', () => {
  isTwoFingerTouch = false;
});

方案2:利用Swiper钩子函数获取原生事件

在Swiper初始化时,通过内置钩子直接获取原生触摸事件,以此判断手指数量并执行逻辑:

const mySwiper = new Swiper('.swiper-container', {
  direction: 'vertical',
  on: {
    touchStart(e) {
      // 标记当前是否为双指触摸
      this.isTwoFinger = e.touches.length === 2;
    },
    touchMove(e) {
      if (this.isTwoFinger) {
        // 基于双指平均位置判断滑动方向
        const avgY = (e.touches[0].clientY + e.touches[1].clientY) / 2;
        if (this.lastAvgY && avgY < this.lastAvgY - 30) {
          this.slideNext();
          this.lastAvgY = null; // 避免重复触发
        } else if (this.lastAvgY && avgY > this.lastAvgY + 30) {
          this.slidePrev();
          this.lastAvgY = null;
        }
        this.lastAvgY = avgY;
      }
    },
    touchEnd() {
      this.isTwoFinger = false;
      this.lastAvgY = null;
    }
  }
});

注意事项

  • 若双指逻辑和Swiper默认滑动冲突,可在双指触摸时通过e.preventDefault()阻止默认行为,但建议添加阈值判断后再执行,避免影响正常单指滑动。
  • 根据不同设备的触摸灵敏度,调整示例中的阈值(如30、50),优化体验。

内容的提问来源于stack exchange,提问作者Rachna Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:35:22