本文翻译自:How to detect escape key press with pure JS or jQuery?
Possible Duplicate: 可能重复:
Which keycode for escape key with jQuery 使用jQuery的escape key的哪个键代码
How to detect escape key press in IE, Firefox and Chrome? 如何在IE,Firefox和Chrome中检测转义按键? Below code works in IE and alerts 27
, but in Firefox it alerts 0
下面的代码适用于IE和警报27
,但在Firefox中它会提醒0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
#1楼
参考:https://stackoom.com/question/E8aH/如何使用纯JS或jQuery检测转义键
#2楼
Using JavaScript you can do check working jsfiddle 使用JavaScript,您可以检查工作jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle 使用jQuery你可以检查工作jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
#3楼
Best way is to make function for this 最好的办法就是为此做好准备
FUNCTION: 功能:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE: 例:
$("#my-div").escape(function () {
alert('Escape!');
})
#4楼
check for keyCode
&& which
& keyup
|| 检查keyCode
&& which
& keyup
|| keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
#5楼
Note: keyCode
is getting deprecated use key
instead. 注意: keyCode
正在被弃用的使用key
。
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
keyCode
is Getting deprecated keyCode
已弃用
It seems
keydown
andkeyup
work, even thoughkeypress
may not 它似乎是keydown
和keyup
工作,即使keypress
可能没有
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery 使用jQuery的escape key的哪个键代码
#6楼
The keydown
event will work fine for Escape and has the benefit of allowing you to use keyCode
in all browsers. keydown
事件适用于Escape,并且允许您在所有浏览器中使用keyCode
。 Also, you need to attach the listener to document
rather than the body. 此外,您需要将侦听器附加到document
而不是正文。
Update May 2016 2016年5月更新
keyCode
is now in the process of being deprecated and most modern browsers offer the key
property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it). keyCode
现在正在被弃用,现在大多数现代浏览器都提供了key
属性,尽管你现在仍然需要支持适当的浏览器支持(在编写当前版本的Chrome和Safari时不支持它) )。
Update September 2018 evt.key
is now supported by all modern browsers. 2018年9月更新 evt.key
现在支持所有现代浏览器。
document.onkeydown = function(evt) { evt = evt || window.event; var isEscape = false; if ("key" in evt) { isEscape = (evt.key === "Escape" || evt.key === "Esc"); } else { isEscape = (evt.keyCode === 27); } if (isEscape) { alert("Escape"); } };
Click me then press the Escape key