试图绑定alt gr键并且它在chrome中不起作用

时间:2018-06-13 10:03:47

标签: jquery google-chrome key-bindings

之前在所有浏览器中都运行良好但由于某些原因ALT GR在chrome中起作用。我完全没有想法让这个工作..

在所有浏览器中使用CTRL + ALT + Q

使用Chrome版本67.0.3396.87(官方版)(64位)



$(document).on("keydown", function(event)
{
    console.log(event.ctrlKey);
    console.log(event.altKey);
        
    // AltGr+Q
    if(event.which === 81 && event.ctrlKey && event.altKey)
    {          
        $("#notes").empty('');
        $("#notes").append("Success!<br/>" , " Event: ", event.which, " ctrlKey: ", event.ctrlKey, " Altkey: ", event.altKey);
        return false;
     }
     else
     {
        $("#notes").empty('');
        $("#notes").append("Fail! <br/>" , " Event: ", event.which, " ctrlKey: ", event.ctrlKey, " Altkey: ", event.altKey);
        return false;
      }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span id="notes">Klick to focus snippet and test keydown event, works well in Explorer/Edge but not in chrome</span>
<div/>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案。我真的不喜欢这个解决方案,因为它有点乱,我不知道它的防弹。任何有关这一点的见解将非常感激,如果有一个外部的方法在这里采取会更干净。

var altgr = false;   
    
    $(document).on("keyup", function (event) {
        if((event.key === "AltGraph"|| event.key ==="Alt")||(event.ctrlKey && event.altKey)){
          altgr=false;
        }
    });

$(document).on("keydown", function(event)
{   
    var altkey = event.key;     
     if((event.key === "AltGraph")||(event.ctrlKey && event.altKey)){
      altgr = true;
     }
     console.log(altgr);
        
    // AltGr+Q
    if(event.which === 81 && altgr)
    {          
        $("#notes").empty('');
        $("#notes").append("Success!<br/>" , " Event: ", event.which, " ctrlKey: ", event.ctrlKey, " Altkey: ", event.altKey);
        return false;
     }
         if(event.which === 87 && altgr)
    {          
        $("#notes").empty('');
        $("#notes").append("Success!<br/>" , " Event: ", event.which, " ctrlKey: ", event.ctrlKey, " Altkey: ", event.altKey);
        return false;
     }
     else
     {
        $("#notes").empty('');
        $("#notes").append("Fail! <br/>" , " Event: ", event.which, " ctrlKey: ", event.ctrlKey, " Altkey: ", event.altKey);
        return false;
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span id="notes">Click to focus snippet and test keydown event, works well in Explorer/Edge but not in chrome</span>
<div/>