macos 用于 cmd+s 和 ctrl+s 的 jquery 按键事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11502122/
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-21 09:20:27  来源:igfitidea点击:

jquery keypress event for cmd+s AND ctrl+s

javascriptjqueryhtmlcssmacos

提问by John Magnolia

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?

是否也可以将其更改为适用于 Mac cmd 键?

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

我试过了,(!(event.which == 115 && (event.cmdKey || event.ctrlKey)) && !(event.which == 19))但这没有用。

回答by spyke

Use the event.metaKeyto detect the Command key

使用event.metaKey检测 Command 键

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

回答by Barlas Apaydin

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

对于检测ctrl+sand cmd+s,您可以使用这种方式:

Working jsFiddle.

工作 jsFiddle。

jQuery:

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)

源(包括所有键盘快捷键和按钮)

回答by Michael_Scharf

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;
});