vue实现h5左右滑动

dom

<div @touchstart="moveStart" @touchmove="onMove" @touchend="moveEnd"></div>

js

data(){
    return {
        startX: 0, // 触摸起始x
        startY: 0, // 触摸起始y
        endX: 0, // 触摸结束x
        endY: 0, // 触摸结束y
        canMove: true, // 是否可以继续滑动
        index: 0 // 控制滑动下标
    }
}
methods(){
    moveStart(e) {
      this.startX = e.targetTouches[0].pageX
      this.startY = e.targetTouches[0].pageY
    },
    onMove(e) {
      this.endX = e.targetTouches[0].pageX
      this.endY = e.targetTouches[0].pageY
      const dValueX = Math.abs(this.startX - this.endX)
      const dValueY = Math.abs(this.startY - this.endY)
      if (dValueX > dValueY) {
        // 水平滑动长度大于纵向滑动长度,那么选择水平滑动,阻止浏览器默认左右滑动事件
        e.preventDefault()
        if (dValueX > 40 && this.startX > this.endX) {
          // 向左划
          if (this.index < this.list.length - 1 && this.canMove) {
            this.canMove = false
            this.index += 1
          }
        } else if (dValueX > 40 && this.index > 0 && this.canMove) {
          this.canMove = false
          this.index -= 1
        }
      } else {
          // 恢复默认事件
        window.event.returnValue = true
      }
    },
    moveEnd(e) {
      this.canMove = true
      this.startX = this.endX = 0
      this.startY = this.endY = 0
    },    
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容