【问题标题】:Finding out the key pressed with ctrl key using jQuery使用 jQuery 找出用 ctrl 键按下的键
【发布时间】:2015-06-02 21:44:58
【问题描述】:

我正在尝试使用 jQuery 找出用 ctrl 键按下的字符,但我无法找出代码。

例如:如果我按 ctrl+a 那么它应该提醒我 ctrl+a 被按下.

我正在使用下面的代码

  $(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 
   }
});

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您必须使用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/

【讨论】:

  • 我不想只知道“a”,我想知道用 ctrl 键按下的任何键。
  • 它仍然没有给出按下的值,警报只显示“Ctrl”和空白键值。
【解决方案2】:
<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>

【讨论】:

  • 你最好使用 e.keyCode 而不是 e.charCode
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多