简体   繁体   English

如何检测javaScript中的点击+特定按键?

[英]How to detect click+specific key press in javaScript?

I am new to JavaScript and learning event handlers.我是 JavaScript 的新手,正在学习事件处理程序。 How to detect click + specific key pressed concurrently?如何检测同时按下的点击+特定键? For example click+D , using pure (vanilla) js.例如click+D ,使用纯(香草)js。

Edit:编辑:
I tried this way but its not detecting the click event when key is pressed.我试过这种方式,但它在按下键时没有检测到点击事件。 The console.log("key "+keyPressed) statement is also executed continuously while key is in pressed state. console.log("key "+keyPressed)语句也在按下键时连续执行 state。

keyPressed=false;

function keyDown(event) {
    var x = event.key;
  
    if (x == "a" || x == "A") { 
         keyPressed=true;
         console.log("key "+keyPressed);
    }

  }

function keyUp(event){

  keyPressed=false;
  
  console.log("key "+keyPressed);

}

 function clickHelper(event){
  console.log("---");
    if(keyPressed){
      console.log("*****");
    }
 } 

IIRC you cannot use one event to detect if the mouse is held down AND a button is clicked. IIRC 您不能使用一个事件来检测是否按住鼠标并单击按钮。 However, you can set a property called mouseDown of the document and register an event listener for mouse state.但是,您可以设置文档的一个名为mouseDown的属性,并为鼠标 state 注册一个事件监听器。

var mouseDown = 0;
document.body.onmousedown = function () {
    ++mouseDown;
};
document.body.onmouseup = function () {
    --mouseDown;
};

document.body.onkeydown = function (e) {
    if (mouseDown && e.key === 'd') {
        alert('D was pressed while clicking');
    }
};

I used some code from this stackoverflow post for this.为此,我使用了这个 stackoverflow 帖子中的一些代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM