How to detect that Ctrl+R was pressed?

2019-01-17 10:50发布

I'm coding a function in jquery that executes if Ctrl+R is pressed but I can't seem to find out what the left and right ctrl keycodes are... Can someone please help?

UPDATE

    ///this works
    $(document).keydown(function(e){
      if(e.keyCode==17){alert("control was pressed")};
 });

Next Question-- How do I link control key press and another key press to execute a function?

  if(e.keyCode==17){llCtrlPress=1};
   if(e.keyCode==97 && llCtrlPress=1){DO SOMETHING}
  ????????????

That seems like it would work fine but then how do I set llCtrlpress back to '0' on keyup?

8条回答
时光不老,我们不散
2楼-- · 2019-01-17 11:06

You have to use the keydown function to trap Ctrl characters. Here is my implementation of Ctrl+A:

    $(document).keydown(function(e) {
        if (e.keyCode == 65 && e.ctrlKey) {
            alert('ctrl A');
        }
    });

Ctrl-R is tougher because in most browsers, that is Reload Page, which means the javascript doesn't run, the page is refreshed.

Just a note as well, the keyCode value are different in the keydown/keyupup functions than in the keypress functions.

EDIT: Removed ctrl variable, forgot about ctrlKey

查看更多
我命由我不由天
3楼-- · 2019-01-17 11:06
 $(document).ready(function () {
     $(document).keyup(function (e) {
         if (e.keyCode == 81 && e.ctrlKey) { //CTRL+Q
             alert("CTRL+Q");
         } else if (e.keyCode == 27) { //ESCAPE
             alert("escape");
         } else if (e.keyCode == 67 && e.altKey) { // ALT+C
           alert("ALT+C");
        }     
    });
});

key codes

查看更多
Emotional °昔
4楼-- · 2019-01-17 11:12

There is a boolean property called ctrlKey that you should be able to use here...

$(document).keypress(function(e) { 
   alert("Ctrl is pressed: " + e.ctrlKey); 
}); 
查看更多
Emotional °昔
5楼-- · 2019-01-17 11:16

Here is an entire list of keycodes that you can use.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-17 11:16

Use event.key and modern JS!

$(document).keypress(function(event) {
    if (event.key === "r" && event.ctrlKey) {
        // Do something
    }
});

or without jQuery:

document.addEventListener("keypress", function onEvent(event) {
    if (event.key === "r" && event.ctrlKey) {
        // Do something better
    }
});

Mozilla Docs

Supported Browsers

查看更多
相关推荐>>
7楼-- · 2019-01-17 11:19

The Key Code for Ctrl key is 11.

$(document).keypress(function(e) { 


  alert("Ctrl is pressed: " + e.ctrlKey); 
}); 
查看更多
登录 后发表回答