jquery: keypress, ctrl+c (or some combo like that)

2019-01-03 02:39发布

I'm trying to create shortcuts on the website i'm making. I know I can do it this way:

if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}

But the example below is easier and less code, but it's not a combo keypress event:

$(document).keypress("c",function() {
  alert("Just C was pressed..");
});

So I wanna know if by using this second example, I could do something like:

$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});

is this possible? I've tried it and it didn't work, what am i doing wrong.

8条回答
萌系小妹纸
2楼-- · 2019-01-03 03:28

I couldn't get it to work with .keypress(), but it worked with the .keydown() function like this:

$(document).keydown(function(e) {
    if(e.key == "c" && e.ctrlKey) {
        console.log('ctrl+c was pressed');
    }
});
查看更多
叛逆
3楼-- · 2019-01-03 03:33

Try the Jquery Hotkeys plugin instead - it'll do everything you require.

jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.

This plugin is based off of the plugin by Tzury Bar Yochay: jQuery.hotkeys

The syntax is as follows:

$(expression).bind(types, keys, handler); $(expression).unbind(types, handler);

$(document).bind('keydown', 'ctrl+a', fn);

// e.g. replace '$' sign with 'EUR'
// $('input.foo').bind('keyup', '$', function(){   
//      this.value = this.value.replace('$', 'EUR'); });
查看更多
登录 后发表回答