禁用某些键的默认操作

pti*_*rs9 1 javascript keyboard events

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

    //space pressed
    if (keyID == 32) {
        anotherFunction();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

JCO*_*611 14

它应该工作.只是为了确保,试试这个:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)