思路
- 放棄click事件,通過判斷按的時長來決定是單擊還是長按
- 使用touchstart和touchend事件
- 在touchstart中開啟一個定時器,比如在700ms后顯示一個長按菜單
- 在touchend中清除這個定時器,這樣如果按下的時間超過700ms,那么長按菜單已經顯示出來了,清除定時器不會有任何影響;如果按下的時間小於700ms,那么touchstart中的長按菜單還沒來得及顯示出來,就被清除了。
由此我們可以實現模擬的長按事件了。
let timer = null
let startTime = ''
let endTime = ''
document.addEventListener('touchstart', function () {
startTime = +new Date()
timer = setTimeout(function () {
// 處理長按事件
console.log('long');
}, 700)
})
document.addEventListener('touchend', function () {
endTime = +new Date()
clearTimeout(timer)
if (endTime - startTime < 700) {
// 處理點擊事件
console.log('no long');
}
})