Javascript 如何使用纯 JS 或 jQuery 检测转义键按下?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3369593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:20:51  来源:igfitidea点击:

How to detect escape key press with pure JS or jQuery?

javascriptjquerykeyeventjquery-events

提问by Mithun Sreedharan

Possible Duplicate:
Which keycode for escape key with jQuery

可能的重复:
使用 jQuery 转义键的键码

How to detect escape key press in IE, Firefox and Chrome? Below code works in IE and alerts 27, but in Firefox it alerts 0

如何在 IE、Firefox 和 Chrome 中检测转义键按下?下面的代码适用于 IE 和警报27,但在 Firefox 中它会发出警报0

$('body').keypress(function(e){
    alert(e.which);
    if(e.which == 27){
        // Close my modal window
    }
});

回答by Jigar Joshi

Note: keyCodeis getting deprecateduse keyinstead.

注:keyCode越来越过时的使用key来代替。

function keyPress (e) {
    if(e.key === "Escape") {
        // write your logic here.
    }
}

Here is jsfiddle

这是jsfiddle



keyCodeis Getting deprecated

keyCode正在被弃用

It seems keydownand keyupwork, even though keypressmay not

它似乎keydownkeyup工作,即使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 转义键的键码

回答by Tim Down

The keydownevent will work fine for Escape and has the benefit of allowing you to use keyCodein all browsers. Also, you need to attach the listener to documentrather than the body.

keydown事件适用于 Escape,并具有允许您keyCode在所有浏览器中使用的好处。此外,您需要将侦听器附加到document而不是主体。

Update May 2016

2016 年 5 月更新

keyCodeis now in the process of being deprecated and most modern browsers offer the keyproperty 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 2018evt.keyis now supported by all modern browsers.

evt.key所有现代浏览器现在都支持2018 年 9 月更新

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

回答by Subodh Ghulaxe

Using JavaScriptyou can do check working jsfiddle

使用JavaScript,您可以检查工作jsfiddle

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert('Esc key pressed.');
    }
};

Using jQueryyou can do check working jsfiddle

使用jQuery,您可以检查工作jsfiddle

jQuery(document).on('keyup',function(evt) {
    if (evt.keyCode == 27) {
       alert('Esc key pressed.');
    }
});

回答by jAndy

check for keyCode&& which& keyup|| keydown

检查keyCode&& which& keyup||keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});

回答by Ivijan Stefan Stipi?

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!');
})

回答by Tarik

Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.

下面的代码不仅禁用 ESC 键,还检查按下它的条件,并根据情况,它是否会执行操作。

In this example,

在这个例子中,

e.preventDefault();

will disable the ESC key-press action.

将禁用 ESC 按键操作。

You may do anything like to hide a div with this:

你可以做任何事情,比如用这个隐藏 div:

document.getElementById('myDivId').style.display = 'none';

Where the ESC key pressed is also taken into consideration:

按下 ESC 键的位置也被考虑在内:

(e.target.nodeName=='BODY')

You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.

如果您想将其应用于所有人,则可以删除此 if 条件部分。或者您可以在此处将 INPUT 定位为仅在光标位于输入框中时应用此操作。

window.addEventListener('keydown', function(e){
    if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
        e.preventDefault();
        return false;
    }
}, true);

回答by Duan Walker

i think the simplest way is vanilla javascript:

我认为最简单的方法是 vanilla javascript:

document.onkeyup = function(event) {
   if (event.key === 27){
     //do something here
   }
}