移动端-touch与mouse事件

1,854 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第 6 天,点击查看活动详情

移动端事件

一、touch事件

  • 1、touchstart touchstart 类似 mousedown 手指在元素按下

  • 2、touchmove

touchmove 类似 mousemove 手指在元素按下之后,在屏幕中移动

  • 3、touchend

touchend 类似 mouseup 手指在元素按下之后,在屏幕中抬起

// touchstart --> mousedown 手指在元素按下
// touchmove --> mousemove 手指在元素按下之后,在屏幕中移动
// touchend --> mouseup 手指在元素按下之后,在屏幕中抬起
box1.addEventListener("touchstart",()=>{
    console.log(1);
});
box1.addEventListener("touchmove",(e)=>{
    console.log(2,e.target);
});
box1.addEventListener("touchend",(e)=>{
    console.log(3,e.target);
});
// mousedown 鼠标按下
// mousemove 鼠标移动
// mouseup 鼠标抬起
box1.addEventListener("mousedown",()=>{
    console.log(1);
});
box1.addEventListener("mousemove",()=>{
    console.log(2);
});
box1.addEventListener("mouseup",()=>{
    console.log(3);
});
  • touch与mouse的区别

    1、在屏幕中移动
    手机端要移动元素必须要先按下才能移动元素,触发 touchmove
    pc端 只需要鼠标移动到元素上就会触发 mousemove

    2、在屏幕中抬起
    手机端 如果手指移动到其他区域,抬起手指依旧会触发touchend
    pc端 如果鼠标移出元素区域(鼠标没有指在监听元素上)后抬起,不会触发mouseup

二、阻止默认事件

在移动端,mouse 事件也会被触发。
设置阻止touch的默认事件:

document.addEventListener("touchstart",(e)=>{
    e.preventDefault();
})

上面代码会会抛出问题:[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive.
简单来说,就是不允许阻止默认事件。\

document/documentElement/document.body: 默认情况下不允许阻止 touch 的默认事件

如果必须要阻止默认事件的话,可以做以下设置
passive : 是否不允许设置默认事件

document.addEventListener("touchstart",(e)=>{
    e.preventDefault();
},{
    passive: false
})

三、阻止默认事件带来的问题

上面,设置阻止默认事件后mouse事件就不会触发了。
总的来说,阻止touch的默认事件会带来的问题,如下:

1、touchstart
1)所有的mouse事件都会被屏蔽,包括 href
2)焦点获取和失去焦点
3)阻止滚动条滚动
4)多指缩放失效
5)阻止系统菜单

2、touchmove
1)阻止滚动条滚动
2)多指缩放失效

3、touchend
1)所有的mouse事件都会被屏蔽,包括 href
1)焦点获取和失去焦点