javascript 如何捕获键盘事件来自哪些键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6504914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:53:21  来源:igfitidea点击:

How can I capture keyboard events are from which keys?

javascripthtml

提问by Vimal Basdeo

I googled and got the following codes on the Net.However, when I press a keyboard key,it is not displaying me an alert box. I want to get which character I have pressed in the alert box. How do I fix this?

我在网上搜索并获得了以下代码。但是,当我按下键盘键时,它没有显示警告框。我想知道我在警告框中按下了哪个字符。我该如何解决?

<script type="text/javascript">

var charfield=document.getElementById("char")
charfield.onkeydown=function(e){
var e=window.event || e;
alert(e.keyCode);
}

</script>
</head>

<body id="char">

</body>
</html>

回答by Tim Down

If you want to get the character typed, you must use the keypressevent rather than the keydownevent. Something like the following:

如果要获得键入的字符,则必须使用keypress事件而不是keydown事件。类似于以下内容:

var charfield = document.getElementById("char");
charfield.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode > 0) {
        alert("Typed character: " + String.fromCharCode(charCode));
    }
};

回答by Pranay Rana

try this jquery code

试试这个 jquery 代码

  $("body").keypress(function(e){
        alert(e.which);
    });

回答by K6t

You'll get the appropriate key code:

您将获得相应的密钥代码:

charfield.onkeydown=function(evt){
    var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
    alert(keyCode);
}

回答by natlee75

I can't off the top of my head think of a good situation in which to use the "on some event" method of a DOM element to deal with events on that element.

我无法想到使用 DOM 元素的“on some event”方法来处理该元素上的事件的好方法。

The best practice is to use addEventListener(or attachEventin older versions of Internet Explorer) like so:

最佳实践是像这样使用addEventListener(或attachEvent在旧版本的 Internet Explorer 中):

charfield.addEventListener('keydown', function (e) { alert(e.keyCode); }, false);

If you want to account for attachEventas well:

如果您还想考虑attachEvent

(function (useListen) {
    if (useListen) {
        charfield.addEventListener('keydown', alertKeyCode, false);
    } else {
        charfield.attachEvent('onkeydown', alertKeyCode);
    }
})(charfield.addEventListener);

function alertKeyCode(e) {
    alert(e.keyCode);
}