实现思路:通过对触摸开始、移动、结束的监听来判断用户的操作是不是长按。如果触发了移动事件,说明是滑动,如果触摸开始和结束的时间间隔不超过380ms
说明是点击,这里就要借助超时器来实现了,否则的话就是长按了。下面来看代码实现:
const box=document.documentElement
function a(){console.log('longtab')}
function addLongtabListener(target,callback){
let timer=0 // 初始化timer
target.ontouchstart=()=>{
timer=0 // 重置timer
timer=setTimeout(()=>{callback();timer=0},380) // 超时器回调能成功执行,说明是长按
}
target.ontouchmove=()=>{
clearTimeout(timer) // 如果来到这里,说明是滑动,清除超时器,不执行回调
timer=0
}
target.ontouchend=()=>{ // 到这里如果timer有值,说明此触摸时间不足380ms,是点击,清除超时器,不执行回调
if(timer){clearTimeout(timer)}
}
}
addLongtabListener(box,a)