vue 判断组合键keyup/keydown

 
 
vue中如何组合键被按
如果是功能键(ctrl,alt,shift)+字母


复制代码
1
2
3
4
function (e) {
   if(e.key=="z" && e.ctrlKey==true){
  }
}
通过上面的代码即可实现.

如果,是包括多个字母键,就不能像上面这么写,需要用一个变量来做开头,进行判断,如下:


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
created() {
      let self = this;
      let code = 0
      let code2 = 0
      document.onkeydown = function (e) {
        let evn = e || event;
        let key = evn.keyCode || evn.which || evn.charCode;
        // F2
        if (key === 113) {
           ......
        }
        //F5
        if (key === 116) {
          e.preventDefault() //禁止默认事件
          ......
        }
        //  c
        if (key === 67) {
          code2 = 1
        }
        //  j
        if (key === 74) {
          code2 = 2
        }
        //  alt
        if (key === 18) {
          code = 1
        }
        // Alt + C  
        if (code === 1 && code2 === 1) {
          ......
        }
        // Alt+ j
        if (code === 1 && code2 === 2) {
         ......
        }
      }
      // keyup时及时的 归零
      document.onkeyup = function (e) {
        if (e.keyCode === 67) {
          code2 = 0;
        }
        if (e.keyCode === 18) {
          code = 0;
        }
        if (e.keyCode === 74) {
          code2 = 0;
        }
        if (e.keyCode === 88) {
          code2 = 0;
        }
      }
    },
==================
遇到的问题
  • 只能获取到键盘(such as:F10)的keydown事件,不能获取到keyup事件。
    WTF
    原来是忘了禁止按键的默认事件了。
    加上 e.preventDefault() ,就可以监听到了
参考:https://blog.csdn.net/weixin_33991727/article/details/87783424
原文地址:https://www.cnblogs.com/Programmer-bao/p/11218099.html