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
410 views
in Technique[技术] by (71.8m points)

javascript - Handling 'ctrl+s' keypress event for browser

I was trying to implement the CTRL+S feature for a browser based application. I made a search and came across two scripts in the following to questions

Best cross-browser method to capture CTRL+S with JQuery?
Ctrl+S preventDefault in Chrome

However, when I tried to implement it, it worked but, I still get the default browser save dialog box/window.

My Code:For shortcut.js:

 shortcut.add("Ctrl+S",function() {
     alert("Hi there!");
 },
 {
     'type':'keydown',
     'propagate':false,
     'target':document
});

jQuery hotkeys.js:

$(document).bind('keydown', 'ctrl+s', function(e) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
});

I believe e.preventDefault(); should do the trick, but for some reason it doesn't work. Where am I going wrong.Sorry if it is simple, still learning jJvascript.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You don't need any of those libraries, just try this:

$(document).on('keydown', function(e){
    if(e.ctrlKey && e.which === 83){ // Check for the Ctrl key being pressed, and if the key = [S] (83)
        console.log('Ctrl+S!');
        e.preventDefault();
        return false;
    }
});

The problem was that your code halted at the alert(), preventing your function from interrupting the save dialogue.

(Still uses jQuery)


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

...