正常模擬一個長按事件,我們是通過 toushstart & touchend 觸發(fā)時間差來實(shí)現(xiàn), 今天在開發(fā)組件庫時看到字節(jié)的組件庫模擬長按事件的實(shí)現(xiàn), 記錄一下
<body>
<button>長按</button>
<script>
let timer
document.querySelector('button').addEventListener('touchstart', handleTouchStart)
document.querySelector('button').addEventListener('click', handleClick)
function handleTouchStart() {
timer = setTimeout(() => {
timer = 0
console.log('longpress')
}, 1000)
}
function handleClick() {
if (timer !== 0) {
clearTimeout(timer)
}
}
</script>
</body>