【问题标题】:Any way to prevent/disable CTRL + [key] shortcuts in the browser?有什么方法可以防止/禁用浏览器中的 CTRL + [key] 快捷键?
【发布时间】:2014-07-15 17:37:06
【问题描述】:

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

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

目前我不得不严厉禁止控件中有任何 CTRL 键。我已经将“蹲伏”设置为 C,这也很常见,但我也有关于制作 MMORPG 风格游戏的想法,在该游戏中,您将拥有多个动作条,并且由于 CTRL 不可行而无法进行很多组合。

【问题讨论】:

  • 收听keydowns;如果键匹配,则event.preventDefault() 并调用适当的操作。或者,您可以查看mousetrap,它可以说是 JavaScript 最好的键捕获库。

标签: javascript html


【解决方案1】:

注意:在 Chrome 中 Ctrl+W 为“保留”,使用window.onbeforeunload

注意:Chrome 需要设置event.returnValue

在此代码中,document.onkeydown 用于旧浏览器,window.onbeforeunload 用于 Chrome 和 Firefox

试试这个(禁用 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;
    }
};

【讨论】:

  • 您好,我不确定是否将其标记为正确,因为我发现其他地方说明您无法阻止 CTRL+W 和其他一些。这适用于 CTRL+S,但不适用于 CTRL+W
  • onkeydown 部分似乎在 Chrome v72 和 Firefox v65 中都不起作用(至少在 xubuntu v18.04.1 上)。
  • @ArturKlesun 更新代码,Chrome 需要设置event.returnValue .... 注意:document.onkeydown 被旧浏览器使用
猜你喜欢
  • 2014-06-22
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 2014-04-18
  • 1970-01-01
  • 2011-04-04
相关资源
最近更新 更多