最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I capture keyboard events are from which keys? - Stack Overflow

programmeradmin4浏览0评论

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>

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>
Share Improve this question edited Aug 5, 2017 at 9:35 Supreeth 377 bronze badges asked Jun 28, 2011 at 10:17 Manish BasdeoManish Basdeo 6,26923 gold badges72 silver badges102 bronze badges 1
  • Maybe it will be helpful: stackoverflow.com/questions/302122/… – Kamil Commented Jun 28, 2011 at 10:19
Add a comment  | 

4 Answers 4

Reset to default 9

If you want to get the character typed, you must use the keypress event rather than the keydown event. Something like the following:

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

try this jquery code

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

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.

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

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

If you want to account for attachEvent as well:

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

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

You'll get the appropriate key code:

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

评论列表(0)

  1. 暂无评论