按键不响应字符代码
Keypress not responding to character codes
$(document).keypress(function(e) {
if(e.which == 32) {
alert('You pressed spacebar!');
}
});
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
$(document).keypress(function(e) {
if(e.which == 40) {
alert('You pressed down arrow!');
}
});
这是我的 javascript 文件。没有 CSS 而 HTML 只是一个空白骨架。
它读取回车键和空格键没问题,但向下箭头、向上箭头或几乎所有我按下的不是回车键或空格键的键都没有注册?
如何解决这个问题?
感谢任何帮助。
箭头键不会生成 keypress
事件。它们生成 keydown
和 keyup
事件。
请注意,虽然字母键会生成 keypress
,但 which
值可能不是您期望的值。例如,在我的浏览器和操作系统上,按 a 键会生成 which = 65
,这是 A
的字符代码,而不是 a
。键代码是 key 代码,而不是 character 代码。更多关于 this no-longer-maintained, but still quite useful, page.
实例: (我添加了一个 return false
来防止默认处理,否则 Stack Snippet window 会滚动周围,但这不是接收事件所必需的)
$(document).keypress(function(e) {
if(e.which == 32) {
display('You pressed spacebar!');
return false;
}
});
$(document).keypress(function(e) {
if(e.which == 13) {
display('You pressed enter!');
return false;
}
});
$(document).keydown(function(e) {
if(e.which == 40) {
display('You pressed down arrow!');
return false;
}
});
function display(msg) {
$("<p>").text(msg).appendTo(document.body);
}
p {
margin: 0;
}
<p>Click this pane to focus it, then press spacebar, Enter, or down-arrow</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$(document).keypress(function(e) {
if(e.which == 32) {
alert('You pressed spacebar!');
}
});
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
$(document).keypress(function(e) {
if(e.which == 40) {
alert('You pressed down arrow!');
}
});
这是我的 javascript 文件。没有 CSS 而 HTML 只是一个空白骨架。
它读取回车键和空格键没问题,但向下箭头、向上箭头或几乎所有我按下的不是回车键或空格键的键都没有注册?
如何解决这个问题?
感谢任何帮助。
箭头键不会生成 keypress
事件。它们生成 keydown
和 keyup
事件。
请注意,虽然字母键会生成 keypress
,但 which
值可能不是您期望的值。例如,在我的浏览器和操作系统上,按 a 键会生成 which = 65
,这是 A
的字符代码,而不是 a
。键代码是 key 代码,而不是 character 代码。更多关于 this no-longer-maintained, but still quite useful, page.
实例: (我添加了一个 return false
来防止默认处理,否则 Stack Snippet window 会滚动周围,但这不是接收事件所必需的)
$(document).keypress(function(e) {
if(e.which == 32) {
display('You pressed spacebar!');
return false;
}
});
$(document).keypress(function(e) {
if(e.which == 13) {
display('You pressed enter!');
return false;
}
});
$(document).keydown(function(e) {
if(e.which == 40) {
display('You pressed down arrow!');
return false;
}
});
function display(msg) {
$("<p>").text(msg).appendTo(document.body);
}
p {
margin: 0;
}
<p>Click this pane to focus it, then press spacebar, Enter, or down-arrow</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>