按下上下键时是否触发了功能?

时间:2017-05-13 17:50:28

标签: javascript function if-statement addeventlistener keycode

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

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之外的任何键时,显示“已按下一个键”的控制台日志会激活。可能导致这种情况的原因是什么?

先谢谢你。

1 个答案:

答案 0 :(得分:1)

改为使用keyup事件。

  

并未针对所有浏览器中的所有键(例如ALT,CTRL,SHIFT,ESC,箭头)触发onkeypress事件。要仅检测用户是否按下了某个键,请改用onkeydown事件,因为它适用于所有键。

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