touchstart、touchmove、touchend与click冲突

发布时间 2023-06-15 13:55:00作者: 未来的山大王

在移动端,一个元素既注册有滑动事件,又注册有点击事件时就会出现一些问题。

滑动事件的优先级是大于点击事件的,而当我们只想执行点击事件而不想触发滑动时间时,就必须做个处理
事件执行顺序:
touchstart →touchmove →touchend→click
所以当我们执行点击事件时,其实在执行点击事件之前,就已经执行了滑动事件了。如果滑动事件的逻辑和点击事件的逻辑不一样,这样就会出现问题。
上网找了很久终于找到一个方法,就是通过活动距离来判断,当滑动距离大于自己设定的距离时,就执行滑动事件,否则就不执行。

 

        touchstart (e) {
            this.startX = e.touches[0].clientX
        },
        touchmove (e) {
            this.moveX = e.touches[0].clientX
            // 如果有滑动距离,则将isTouch设为true
            if (this.moveX) {
                this.isTouch = true
            }
        },
        touchEnd () {
            if (this.isTouch) {
                if (this.startX - this.moveX < -50 && this.moveX) { // 右滑触发
                    this.getData()
                } else if (this.startX - this.moveX > 50 && this.moveX) { //左滑触发
                    this.getData()
                }
            }
            this.startX = 0
            this.moveX = 0
            this.isTouch = false
        },