使用鍵盤事件來改變狀態
1
|
<div class="box"></div>
|
1
2
3
4
5
|
.box{
width: 30px;
height: 30px;
background-color: #ccc;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//按下鍵盤的那個剎那
$(window).keydown(function(event){
if(event.which == 90){
$('.box').css('background-color', 'red');
}
});
//只會針對可以輸出文字符號的按鍵有效
$(window).keypress(function(event){
if(event.which == 90){
$('.box').css('background-color', 'green');
}
});
//指放開鍵盤的那個剎那
$(window).keyup(function(event){
if(event.which == 90){
$('.box').css('background-color', 'blue');
}
});
|
event.which跟event.keyCode是一樣的,但是event.keyCode寫法較舊,event.which比較標準化
ascii碼鍵盤對應表
字母 |
鍵碼值 |
字母 |
鍵碼值 |
字母 |
鍵碼值 |
字母 |
鍵碼值 |
a |
97 |
A |
65 |
1 |
49 |
Enter |
13 |
b |
98 |
B |
66 |
2 |
50 |
倒退鍵 |
8 |
c |
99 |
C |
67 |
3 |
51 |
Ctrl |
17 |
d |
100 |
D |
68 |
4 |
52 |
Esc |
27 |
e |
101 |
E |
69 |
5 |
53 |
Delete |
46 |
f |
102 |
F |
70 |
6 |
54 |
Alt |
18 |
g |
103 |
G |
71 |
7 |
55 |
Tab |
9 |
h |
104 |
H |
72 |
8 |
56 |
Shift |
16 |
i |
105 |
I |
73 |
9 |
57 |
空白鍵 |
32 |
j |
106 |
J |
74 |
0 |
48 |
/ |
191 |
k |
107 |
K |
75 |
F1 |
112 |
> |
190 |
l |
108 |
L |
76 |
F2 |
113 |
< |
189 |
m |
109 |
M |
77 |
F3 |
114 |
' |
222 |
n |
110 |
N |
78 |
F4 |
115 |
; |
186 |
o |
111 |
O |
79 |
F5 |
116 |
] |
221 |
p |
112 |
P |
80 |
F6 |
117 |
[ |
219 |
q |
113 |
Q |
81 |
F7 |
118 |
= |
187 |
r |
114 |
R |
82 |
F8 |
119 |
- |
189 |
s |
115 |
S |
83 |
F9 |
120 |
` |
192 |
t |
116 |
T |
84 |
F10 |
121 |
|
|
u |
117 |
U |
85 |
F11 |
122 |
|
|
v |
118 |
V |
86 |
F12 |
123 |
|
|
w |
119 |
W |
87 |
左鍵 |
37 |
|
|
x |
120 |
X |
88 |
上鍵 |
38 |
|
|
y |
121 |
Y |
89 |
右鍵 |
39 |
|
|
z |
122 |
Z |
90 |
下鍵 |
40 |
|
|
讓ascii碼轉回字母
1
|
$("p").text(String.fromCharCode(90));
|
輸出結果:
其他相關