Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - Overriding shortcut keys in Firefox and Chrome

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

My override 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){}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Here is the 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

Without Jquery:

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

Here is a JSFIDDLE of it working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...