2016-05-29 58 views
1

如何检测ctrl+q使用JavaScript,这是我的代码如何检测CTRL + Q在JavaScript

<body> 
    <p id="x"></p> 
    <script> 
     window.onkeydown = function() {detect(event);} 
     window.onkeypress = function() {res(event);} 
     var act = false; 
     function detect(event) { 
      if(event.ctrlKey) { 
       act = true; 
      } 
      else 
       act = false; 
     } 
     function res(event) { 
      if(act) { 
       document.getElementById("x").innerHTML = "ctrl " + String.fromCharCode(event.which); 
      } 
      else 
       document.getElementById("x").innerHTML = String.fromCharCode(event.which); 
     } 
    </script> 
</body> 

我想只有JavaScript做。

+3

这个问题已经被问:参见[如何找到的,出了什么字符键,是压(HTTP :?//stackoverflow.com/questions/1846599/how-to-find-out-what-c​​haracter-key-is-pressed) –

+0

@KevinWallis因此,我们将其标记:) – dbf

回答

5

您可以使用下面的函数检测它:

document.addEventListener("keydown", function (event) { 
    event.stopPropagation(); 
    event.preventDefault(); 

    if(event.ctrlKey && event.keyCode == 81) 
    { 
    console.log("CTRL + Q was pressed!"); 
    } 
    else 
    { 
    console.log("Something else was pressed."); 
    } 
}); 

stopPropagation()preventDefault()来电防止出现浏览器的默认行为。

如果你想检测其他键,这个网页是相当有用的:http://asquare.net/javascript/tests/KeyCode.html

+0

这个代码是如何发现问题:为什么按Ctrl + b ,不工作的console.log( “CTRL + Q按下!”);? – Ehsan

+0

@ehsan'键代码== 81'指Q键。 B键比81 – 2016-09-21 23:34:44

+0

其他东西@ehsan是。 keyCode'81'是'Q'键。我已经在我的答复中提到,提供的链接是决定其他键的'keyCodes'有用。 – starbeamrainbowlabs