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
相关产品推荐
相关产品推荐

