正常模拟一个长按事件,我们是通过 toushstart & touchend 触发时间差来实现, 今天在开发组件库时看到字节的组件库模拟长按事件的实现, 记录一下
<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>