Javascript capturing ctrl+alt+c

2020-07-25 10:08发布

In my web app I want to use ctrl+alt+c as hotkey.

I read bunch of Stack Overflow articles and came up with below solution

$(document).keydown(function(e){
   if(e.ctrlKey && e.altKey && e.which == 99){
     e.preventDefault();
     window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
   }
});

This is not working in chrome. I tried debugging.

What I noticed is as soon as I press ctrl key it goes into function and as if condition fails it is coming out.

How can I get this to work.

2条回答
forever°为你锁心
2楼-- · 2020-07-25 10:31

Use the event keypress instead. Example on jsFiddle.

$(document).keypress(function(e)
{
    if (e.which == 8354) // ctrl+alt+c
    {
       e.preventDefault();
       console.log("success");
    }
    else
    {
        console.log("fail");
    }
    console.log(e);
});
查看更多
戒情不戒烟
3楼-- · 2020-07-25 10:45

There are two mistakes in you code

1st : keycode of c is 67
2nd : text variable is undefined.

So the final code would be

$(document).keydown(function(e){
   if(e.ctrlKey && e.altKey &&  e.which == 67){
      e.preventDefault();
       prompt("Copy to clipboard: Ctrl+C, Enter","text");
   }
  });

you can check the fiddle here

查看更多
登录 后发表回答