禁用特定键的默认操作

4
function keypressCheck() {
    var keyID = event.keyCode;

    //space pressed
    if (keyID == 32) {
        anotherFunction();
    }
}

我希望当按下空格键时,anotherFunction() 能运行,而不会发生页面默认滚动的操作。有没有办法做到这一点?

1个回答

16

应该可以正常工作。为了确保,请尝试以下操作:

function keypressCheck(e) { 
    var e = window.event||e; // Handle browser compatibility
    var keyID = e.keyCode;
    //space pressed
    if (keyID == 32) {
        e.preventDefault(); // Prevent the default action
        anotherFunction();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接