简体   繁体   中英

How can I capture keyboard events are from which keys?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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