vue中如何組合鍵被按
如果是功能鍵(ctrl,alt,shift)+字母
復制代碼
通過上面的代碼即可實現.
如果,是包括多個字母鍵,就不能像上面這么寫,需要用一個變量來做開頭,進行判斷,如下:
復制代碼
==================
遇到的問題
如果是功能鍵(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() ,就可以監聽到了