簡體   English   中英

如何檢測右鍵+左鍵單擊

[英]How to detect right click + left click

我正在建立一個游戲

而我需要做一些事情,當用戶點擊鼠標右鍵, 保存它 ,然后按下左鍵

我怎樣才能檢測到這種行為?

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
}

右鍵單擊每個瀏覽器都有默認菜單,用於刷新頁面,打印,保存等等,但您可以試試這個,可能會阻止默認操作並添加您的自定義。 請寫下答案,如果它會幫助你。

檢查以下代碼

<!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

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

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

雖然有點近,但您可能希望實現回退方法,記錄鼠標按鈕的狀態。

右鍵單擊使用oncontextmenu ,左側只需設置click ,只需禁用它們的默認行為,例如:

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

嘗試

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM