使用阻止默认值来接管空格键

5 javascript jquery

我有一些像这样的代码来接管空格键的功能:

    $(document).keypress(function (e) { 
        e.preventDefault();                            
        if (e.which == 32) {
            // func
        }
    }); 
Run Code Online (Sandbox Code Playgroud)

不幸的是,这破坏了所有密钥的默认设置。

这:

    $(document).keypress(function (e) { 
        if (e.which == 32) {
            e.preventDefault();
            // func
        }
    }); 
Run Code Online (Sandbox Code Playgroud)

不幸的是没有效果。

我怎样才能让它防止默认只有空格键?

谢谢。

TSt*_*per 4

尝试这个:

//e= e || window.event); you may need this statement to make sure IE doesn't keep the orginal event in motion
var code;  
if (e.keyCode) {
 code = e.keyCode;
} else if (e.which) {
 code = e.which;
 }
if (code == 32) {
 if (e.stopPropagation) {
 e.stopPropagation();
 e.preventDefault();
 }
 return false;
}
Run Code Online (Sandbox Code Playgroud)