简体   繁体   English

使用jQuery找出用ctrl键按下的键

[英]Finding out the key pressed with ctrl key using jQuery

I am trying to find out the character pressed with ctrl key using jQuery but I am not able to figure out the code. 我正在尝试使用jQuery查找按ctrl键所按下的字符,但是我无法弄清楚代码。

eg: If I press ctrl + a then it should alert me that ctrl + a is pressed. 例如:如果我按ctrl + a,则应该提醒我按了ctrl + a

I am using below code 我正在使用下面的代码

  $(document).keypress(function(e) {
  if(e.ctrlKey){
     var ch = String.fromCharCode(e.keyCode);
     alert("key pressed ctrl+"+ch); //gives blank value in ch here, I need to know the             character pressed
     alert("key pressed ctrl+"+e.keyCode); //this works but gives me ASCII value of the key 
   }
});

You have to use keydown event to capture the key code reliably: 您必须使用keydown事件来可靠地捕获键代码:

$(document).keydown(function(event) {
    console.log(event);
    if (!event.ctrlKey){ return true; }
    $("#result").text(String.fromCharCode(event.which));
    event.preventDefault();
});

http://jsfiddle.net/7S6Hz/3/ http://jsfiddle.net/7S6Hz/3/

<html>
<head>
<title>ctrlKey example</title>

<script type="text/javascript">

function showChar(e){
  alert(
    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
    + "charCode: " + e.charCode + "\n"
    + "CTRL key pressed: " + e.ctrlKey + "\n"
  );
}

</script>
</head>

<body onkeypress="showChar(event);">
<p>Press any character key, with or without holding down the CTRL key.<br />
You can also use the SHIFT key together with the CTRL key.</p>
</body>
</html>

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

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