简体   繁体   中英

jquery keypress event for cmd+s AND ctrl+s

Using one of the examples from a previous question I have:

$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    $("form input[name=save]").click();
    event.preventDefault();
    return false;
});

Is it also possible to change this to work for the Mac cmd key?

I have tried (!(event.which == 115 && (event.cmdKey || event.ctrlKey)) && !(event.which == 19)) but this didn't work.

Use the event.metaKey to detect the Command key

$(document).keypress(function(event) {
    if (event.which == 115 && (event.ctrlKey||event.metaKey)|| (event.which == 19)) {
        event.preventDefault();
        // do stuff
        return false;
    }
    return true;
});

For detecting ctrl+s and cmd+s , you can use this way:

Working jsFiddle.

jQuery:

var isCtrl = false;
$(document).keyup(function (e) {
 if(e.which == 17) isCtrl=false;
}).keydown(function (e) {
    if(e.which == 17) isCtrl=true;
    if(e.which == 83 && isCtrl == true) {
        alert('you pressed ctrl+s');
    return false;
 }
});

source (includes all keyboard shorcuts and buttons)

This works for me:

$(document).keypress(function(event) {
    if ((event.which == 115 || event.which == 83) && (event.ctrlKey||event.metaKey)|| (event.which == 19)) {
        event.preventDefault();
        // do stuff
        return false;
    }
    return true;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM