按下向上和向下键时触发功能?

To have a function triggered when up and down key is pressed?

我想要它,所以当按下向上或向下键时它会触发不同的功能。到目前为止,这是我的代码:

window.addEventListener('keypress', function(e) {

    console.log("A Key has been pressed");

    /*Sets "key" variable to be the value of the key code of the key pressed*/
    var key = e.which || e.keyCode;

    /*checks if key pressed is the "up" key*/
    if (key === 38){
            functionOne();
            console.log("Up key was Pressed");
        }

    /*checks if key pressed is the "down" key*/     
    else if (key === 40){
            functionTwo();
            console.log("Down key was Pressed");
        }
    })

每当我按下除箭头键、shift、alt、caps、tab 和 f1 - f12 之外的任何键时,显示 "A key has been pressed" 的控制台日志都会激活。可能是什么原因造成的?

先谢谢你。

改为使用 keyup 事件。

The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC, arrows) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

window.addEventListener('keyup', function(e) {
var key = e.which || e.keyCode;
    console.log(key);
    if (key === 38){
        console.log("Up key was Pressed", key );
    }    
    else if (key === 40){
        console.log("Down key was Pressed", key );
    }
    e.preventDefault();
})