0

无法在 Firefox 中禁用 Ctrl+S 的默认行为。无法在 IE 中禁用 Ctrl+P 行为

我的代码有什么问题...?我想不通。谢谢。

// Keyboard shortcuts
var isCtrl = false;
document.onkeyup = function(e) {
    if (e.which === 17) {
        isCtrl = false;
    }
};
document.onkeydown = function(e) {
    if (e.which === 17) {
        isCtrl = true;
    }
    if (e.which === 79 && isCtrl === true) {
        // Ctrl+O
        e.preventDefault();
        Open();
    }
    if (e.which === 83 && isCtrl === true) {
        // Ctrl+S
        e.preventDefault();
        Save();
    }
    if (e.which === 80 && isCtrl === true) {
        // Ctrl+P
        e.preventDefault();
        Print();
    }
    if (e.which === 72 && isCtrl === true) {
        // Ctrl+H
        e.preventDefault();
        Help();
    }
};
4

3 回答 3

0

In short you need to use setTimeout unfortunately, I blogged about this issue in 2014. It's a bit of a hack but it works...

window.onkeypress = function(event)
{
 if (event.ctrlKey && event.key=='s')
 {
  event.preventDefault();
  setTimeout(function() {form_submit(event);},1);
 }
}


function form_submit(event)
{
 alert('trigger your code here...');
}
于 2015-03-17T21:39:53.520 回答
0

您正在使用 e.which 来确定键是否是控制键以及键码本身

这就像在说if(e.which==17 && e.which=79); 看看我在说什么?用于e.ctrlKey确定是否按下了控件 document.onkeyup = function(e) { e.which = e.which || e.charCode;

        isCtrl = e.ctrlKey

};
document.onkeydown = function(e) {
    e.which = e.which || e.charCode;

        isCtrl = e.ctrlKey
    if (e.which === 79 && isCtrl === true) {
        // Ctrl+O
        e.preventDefault();
        Open();
    }
    if (e.which === 83 && isCtrl === true) {
        // Ctrl+S
        e.preventDefault();
        Save();
    }
    if (e.which === 80 && isCtrl === true) {
        // Ctrl+P
        e.preventDefault();
        Print();
    }
    if (e.which === 72 && isCtrl === true) {
        // Ctrl+H
        e.preventDefault();
        Help();
    }
};

javascript

于 2013-09-25T06:08:34.643 回答
0

您可以使用:

e = e || window.event;
e.which = e.which || e.keyCode;

样本:

document.onkeypress = function(e) {
    e = e || window.event;
    e.which = e.which || e.keyCode;
    if (e.which === 79 && e.ctrlKey) {
        // Ctrl+O
        e.preventDefault();
        Open();
    }
    if (e.which === 83 && e.ctrlKey) {
        // Ctrl+S
        e.preventDefault();
        Save();
    }
    if (e.which === 80 && e.ctrlKey) {
        // Ctrl+P
        e.preventDefault();
        Print();
    }
    if (e.which === 72 && e.ctrlKey) {
        // Ctrl+H
        e.preventDefault();
        Help();
    }
};
于 2013-09-25T06:00:00.537 回答