how can i track arrow keys in Chrome and IE?

后端 未结 7 1314
后悔当初
后悔当初 2020-12-06 01:26

Im using foloowing code to track key events

oEvent=window.event || oEvent;
    iKeyCode=oEvent.keyCode || oEvent.which;alert(iKeyCode);

its

7条回答
  •  鱼传尺愫
    2020-12-06 01:41

    Here is a terse formulation:

    document.onkeydown = function(e) {
        switch (e.keyCode) {
            case 37:
                alert('left');
                break;
            case 38:
                alert('up');
                break;
            case 39:
                alert('right');
                break;
            case 40:
                alert('down');
                break;
        }
    };
    

    However, if you are using JQuery, you are better off using e.which, which JQuery "normalizes" to account for cross-browser differences:

    $(document).keydown(function(e) {
        switch(e.which) {
            // the rest is the same
    

提交回复
热议问题