如何区分鼠标“点击”和“拖动”
2022-08-30 01:17:30
我用来处理拉斐尔图上的鼠标点击事件,同时,我需要处理鼠标事件,鼠标拖动由,和拉斐尔组成。jQuery.click
drag
mousedown
mouseup
mousemove
很难区分,因为还包含&,如何在Javascript中区分鼠标“点击”和鼠标“拖动”呢?click
drag
click
mousedown
mouseup
我用来处理拉斐尔图上的鼠标点击事件,同时,我需要处理鼠标事件,鼠标拖动由,和拉斐尔组成。jQuery.click
drag
mousedown
mouseup
mousemove
很难区分,因为还包含&,如何在Javascript中区分鼠标“点击”和鼠标“拖动”呢?click
drag
click
mousedown
mouseup
我认为区别在于,在拖动中和之间有一个,但在点击中没有。mousemove
mousedown
mouseup
你可以做这样的事情:
const element = document.createElement('div')
element.innerHTML = 'test'
document.body.appendChild(element)
let moved
let downListener = () => {
moved = false
}
element.addEventListener('mousedown', downListener)
let moveListener = () => {
moved = true
}
element.addEventListener('mousemove', moveListener)
let upListener = () => {
if (moved) {
console.log('moved')
} else {
console.log('not moved')
}
}
element.addEventListener('mouseup', upListener)
// release memory
element.removeEventListener('mousedown', downListener)
element.removeEventListener('mousemove', moveListener)
element.removeEventListener('mouseup', upListener)
所有这些解决方案要么在微小的鼠标移动时中断,要么过于复杂。
下面是一个使用两个事件侦听器的简单适应性解决方案。Delta 是必须在上下事件之间水平或垂直移动的像素距离,代码才能将其分类为拖动而不是单击。这是因为有时您会在抬起鼠标或手指之前将其移动几个像素。
const delta = 6;
let startX;
let startY;
element.addEventListener('mousedown', function (event) {
startX = event.pageX;
startY = event.pageY;
});
element.addEventListener('mouseup', function (event) {
const diffX = Math.abs(event.pageX - startX);
const diffY = Math.abs(event.pageY - startY);
if (diffX < delta && diffY < delta) {
// Click!
}
});