单击鼠标左键时如何知道按住了哪个键?

时间:2014-08-08 11:03:37

标签: javascript html

当点击鼠标左键时,我不想检测是否有其他键被关闭?我该怎么办? 我用它来检测ctrl + shift但现在我不知道是'A'还是'B'或者两者都被保留了。

if(e.shiftKey && e.ctrlKey) console.log("ctrl+shift key was held when pressing the left mouse button");

我收到的鼠标事件没有持有密钥的keyCode。我想要纯粹的Javascript。

2 个答案:

答案 0 :(得分:0)

也许是这样的(听keydown和keyup):

var keys = [];

$(document).keydown(function(e){
    var index = keys.indexOf(e.keyCode);

    if(index === -1){
        keys.push(e.keyCode);
    }
}).keyup(function(e){
    var index = keys.indexOf(e.keyCode);

    if(index !== -1){
        keys.splice(index, 1);
    }
}).click(function(e){
    console.log(keys);
});

答案 1 :(得分:0)

一个纯粹的JavaScript解决方案是:

var held_key = null;

function key_down(event) {
  var key = event.keyCode || event.which;
  // get string representation of held key
  var keychar = String.fromCharCode(key);
  // store held key in global variable
  held_key = keychar;
}

//revert held_key to null onkeyup
function key_up(event) {
  var key = event.keyCode || event.which;
  held_key = null;
}

window.onload = function() {
  window.onkeydown = key_down;
  window.onkeyup = key_up;
  window.onclick = function(e) {
    // put condition for the key you want here
    if (held_key == 'A') {
      //do something
      console.log('hi!');
    }
  }
}