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() ,就能夠監聽到了
參考:http://www.javashuo.com/article/p-ublmhuxx-kp.html
相關文章
相關標籤/搜索