如何检测右键+左键单击

时间:2016-03-13 17:01:46

标签: javascript jquery

我正在构建游戏

当用户点击鼠标右键, 持有 然后按下左键

时,我需要做一些事情

如何检测此行为?

6 个答案:

答案 0 :(得分:5)

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();
});

答案 1 :(得分:0)

你可以试试这个。

window.oncontextmenu = function () {
  showCustomMenu();
  return false;     // cancel default menu
}
右键单击每个浏览器都有默认菜单,用于刷新页面,打印,保存等等,但您可以试试这个,可能会阻止默认操作并添加您的自定义。 如果有帮助,请写下答案。

答案 2 :(得分:0)

检查以下代码

<!doctype html>
<html lang="en">
<head>
  <input type='button' value='Click Me!!!' id='btnClick'/>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<script>
$(document).ready(function() {
$('#btnClick').mousedown(function(event){
    switch (event.which) {
        case 1:
            alert('Left mouse button pressed');
            break;
        case 2:
            alert('Middle mouse button pressed');
            break;
        case 3:
            alert('Right mouse button pressed');
            break;
        default:
           break;
    }
});
});
</script>

</body>
</html>

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

答案 3 :(得分:0)

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

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

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

答案 4 :(得分:0)

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

var left = 0,
  right = 0;

document.onclick = function() {
  console.log(++left);
  return false;
};

document.oncontextmenu = function() {
  console.log(++right);
  return false;
};

答案 5 :(得分:0)

尝试

var hold=false;

function check(e) {
  if(e.button==2) hold=true;
  if(e.button==0 && hold) console.log('action');
}

function release(e) {
  if(e.button==2) hold=false;
}

function noContext(e) { e.preventDefault(); }
.box { width: 100px; height: 100px; border: 1px solid black;}
Hold right mouse button and press left (on sqare)
<div class="box" 
     onmousedown="check(event)" 
     onmouseup="release(event)"  
     oncontextmenu="noContext(event)"
></div>