要判断鼠标左、中、右键哪个被点击,一般有以下两种方法:
一、使用mousemove和mousedown事件判断
- 在document或者某个元素上绑定mousedown事件;
- 在mousedown事件回调中判断鼠标按下的键位,可以用event.button来获取,其中0表示左键,1表示中键,2表示右键;
- 如果鼠标左键/中键/右键被按下,就记录下来;
- 在mousemove事件回调中判断鼠标是否被拖动了,如果是就不做任何操作,否则就根据记录的结果执行对应的操作。
示例代码:
const mouseState = {left: false, middle: false, right: false};
document.addEventListener('mousedown', function(event) {
switch (event.button) {
case 0:
mouseState.left = true;
break;
case 1:
mouseState.middle = true;
break;
case 2:
mouseState.right = true;
break;
default:
break;
}
});
document.addEventListener('mousemove', function(event) {
if (event.buttons === 0) {
if (mouseState.left) {
// 左键被单击
console.log('左键被单击');
} else if (mouseState.middle) {
// 中键被单击
console.log('中键被单击');
} else if (mouseState.right) {
// 右键被单击
console.log('右键被单击');
}
// 点击事件太短,可能被识别为双击,需要清空之前的状态
mouseState.left = false;
mouseState.middle = false;
mouseState.right = false;
}
});
二、使用contextmenu事件判断
- 在document或者某个元素上绑定contextmenu事件;
- 在contextmenu事件回调中取消默认行为;
- 在contextmenu事件回调中判断鼠标按下的键位,可以用event.button来获取,其中0表示左键,1表示中键,2表示右键;
- 根据键位执行相应的操作。
示例代码:
document.addEventListener('contextmenu', function(event) {
event.preventDefault();
switch (event.button) {
case 0:
// 左键
console.log('左键被单击');
break;
case 1:
// 中键
console.log('中键被单击');
break;
case 2:
// 右键
console.log('右键被单击');
break;
default:
break;
}
});
以上两种方法都能判断鼠标左、中、右键哪个被点击,具体使用哪种方法取决于实际需求。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:js判断鼠标左、中、右键哪个被点击的方法 - Python技术站