解决移动端页面的touchstart和touchmove冲突

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_39457740/article/details/79613996

解决移动端页面的touchstart和touchmove冲突

最近在写一个小项目,移动端的投票工具,作为一个第一次写移动端的菜鸟,问题出现了:

为什么一滑屏幕就触发了一堆touchstart事件呀(摔!!!)

基本概念

  • touchstart事件:当手指触摸屏幕时候触发,即使已经有一个手指放在屏幕上也会触发。
  • touchmove事件:当手指在屏幕上滑动的时候连续地触发。在这个事件发生期间,调用preventDefault()事件可以阻止滚动。
  • touchend事件:当手指从屏幕上离开的时候触发。

看这个架势很眼熟啊,emmm,,,好像和鼠标的事件很相似

  • mousedown:鼠标按下
  • mousemove:鼠标移动
  • mouseup:鼠标抬起

移动之前触发一次点击是难以避免的,在不使用其他类库的前提下有一个很好的解决方法就是进行判断,然后分类解决

解决方法

这个方法参考了这篇文章 来自segmentfahlt的解决方法

    let flag = true;
    $person.on('touchstart touchmove touchend', (event) => {
        switch (event.type) {
                case 'touchstart':
                    flag = true;
                    reak;
                case 'touchmove':
                    flag = false;
                    break;
                case 'touchend':
                    if(flag){
                        // 点击事件
                    }else{
                    // 滑动事件
                    }
                        default:
                            break;
                    }     
                });

猜你喜欢

转载自blog.csdn.net/github_39457740/article/details/79613996