如何检测右键+左键单击

我正在建立一个游戏

当用户点击鼠标右键,按住然后按下左键时,我需要做一些事情

我怎样才能检测到这种行为?

JSfiddle: https ://jsfiddle.net/mkarajohn/pd725ch6/5/

var rightMouseClicked = false; function handleMouseDown(e) { //e.button describes the mouse button that was clicked // 0 is left, 1 is middle, 2 is right if (e.button === 2) { rightMouseClicked = true; } else if (e.button === 0) { //Do something if left button was clicked and right button is still pressed if (rightMouseClicked) { console.log('hello'); //code } } console.log(rightMouseClicked); } function handleMouseUp(e) { if (e.button === 2) { rightMouseClicked = false; } console.log(rightMouseClicked); } document.addEventListener('mousedown', handleMouseDown); document.addEventListener('mouseup', handleMouseUp); document.addEventListener('contextmenu', function(e) { e.preventDefault(); }); 

你可以尝试这个。

 window.oncontextmenu = function () { showCustomMenu(); return false; // cancel default menu } 

右键单击每个浏览器都有默认菜单,用于刷新页面,打印,保存等等,但您可以试试这个,可能会阻止默认操作并添加您的自定义。 请写下答案,如果它会帮助你。

检查下面的代码

           

有关更多参考,请参阅http://www.jquerybyexample.net/2011/04/find-which-mouse-button-clicked-using.html

右键单击使用oncontextmenu ,左侧只需设置click ,只需禁用默认行为,例如:

 var left = 0, right = 0; document.onclick = function() { console.log(++left); return false; }; document.oncontextmenu = function() { console.log(++right); return false; }; 

在事件处理程序中使用MouseEvent.buttons

 .addEventListener("mousedown", function(event){ if ((event.buttons & 3) === 3){ //Do something here } }, true); 

虽然最近有点,你可能想要实现回退方法,记录鼠标按钮的状态。