javascript 覆盖 Firefox 和 chrome 中的快捷键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15911785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:33:16  来源:igfitidea点击:

Overriding shortcut keys in firefox and chrome

javascripthtmlgoogle-chromefirefox

提问by wolfcall

I have a script that is supposed to open a section of a web page and save changes on Ctrl + n and Ctrl + s repectivly I got it working in IE but it doesn't seem to work in firefox and chrome. Any ideas?

我有一个脚本,它应该打开网页的一部分并分别保存 Ctrl + n 和 Ctrl + s 上的更改我让它在 IE 中工作,但它似乎在 firefox 和 chrome 中不起作用。有任何想法吗?

My over ride function.

我的超车功能。

function prevent(e)
{
try{e.stopPropagation();}catch(ex){}
try{e.preventDefault()}catch(ex){}
try{if (e.preventDefault)
        e.preventDefault();
    else {
        e.cancelBubble = true;
        e.returnValue = false;
        e.keyCode = 0;
    }}  catch(ex){}
}

回答by Hunter Mitchell

I have seen the same issue. Some browsers will not allow you to capture certain shortcuts. Look at this https://stackoverflow.com/a/7296303/1366887

我见过同样的问题。某些浏览器不允许您捕获某些快捷方式。看看这个https://stackoverflow.com/a/7296303/1366887

Some key combinations are resticted in Chrome 4, but not in Chrome 3. Look here: https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/chromium-bugs/Ntc1byZXHfU

某些组合键在 Chrome 4 中受到限制,但在 Chrome 3 中不受限制。请看这里:https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/chromium-bugs/Ntc1byZXHfU

Here is the Javascript:

这是Javascript:

$(window).keydown(function(event) {
  if(event.ctrlKey && event.keyCode == 84) { 
    console.log("Hey! Ctrl+T event captured!");
    event.preventDefault(); 
  }
  if(event.ctrlKey && event.keyCode == 83) { 
    console.log("Hey! Ctrl+S event captured!");
    event.preventDefault(); 
  }
});

I have used this numerous times, and it has worked greatly.

我已经多次使用它,并且效果很好。

Here is another rescource you can take a look at: http://unixpapa.com/js/key.html

这是您可以查看的另一个资源:http: //unixpapa.com/js/key.html

Without Jquery:

没有jQuery:

onkeydown = function(e){
  if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
    e.preventDefault();
    //your saving code
  }
}

Here is a JSFIDDLEof it working.

这是它工作的JSFIDDLE