jquery keypress event for cmd+s AND ctrl+s

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

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.

回答1:

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


回答2:

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)



回答3:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!