有什么方法可以阻止/禁用浏览器中的CTRL + [key]快捷方式?

use*_*236 8 html javascript html5

我知道很多人会因为这个问题而生气但是......

我有一个使用WebGL和Pointer Lock API的游戏.由于很多游戏在CTRL上"蹲伏"的性质,我想知道是否有任何可能的方法来阻止CTRL + S和CTRL + W等浏览器快捷方式......

目前,我不得不严厉禁止控件在其中包含任何CTRL键.我已经将'crouch'设置为C,这也很常见,但我也有关于制作MMORPG风格的游戏的想法,你会有几个能力的动作条,由于CTRL不可行,很多组合是不可能的.

Gui*_*nto 24

注意:在Chrome Ctrl+中W是"保留",请使用window.onbeforeunload

试试这个(禁用Ctrl+ WCtrl+ S):

window.onbeforeunload = function (e) {
    // Cancel the event
    e.preventDefault();

    // Chrome requires returnValue to be set
    e.returnValue = 'Really want to quit the game?';
};

//Prevent Ctrl+S (and Ctrl+W for old browsers and Edge)
document.onkeydown = function (e) {
    e = e || window.event;//Get event

    if (!e.ctrlKey) return;

    var code = e.which || e.keyCode;//Get key code

    switch (code) {
        case 83://Block Ctrl+S
        case 87://Block Ctrl+W -- Not work in Chrome and new Firefox
            e.preventDefault();
            e.stopPropagation();
            break;
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 嗨,我不确定是否将其标记为正确,因为我发现其他地方说明您无法阻止 CTRL+W 和其他一些。这适用于 CTRL+S 而不是 CTRL+W (2认同)
  • @ArturKlesun 更新代码,Chrome 需要设置`event.returnValue` .... 注意:旧浏览器使用`document.onkeydown` (2认同)