如何检测退出键按下?

发布于 2024-09-12 19:30:22 字数 253 浏览 4 评论 0原文

如何检测 IE、Firefox 和 Chrome 中的转义键按下情况? 下面的代码在 IE 中工作并发出警报 27,但在 Firefox 中则发出警报 0

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

dawn曙光 2024-09-19 19:30:23

使用 JavaScript 您可以检查工作jsfiddle

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

使用 jQuery 你可以检查工作jsfiddle

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

Using JavaScript you can do check working 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(document).on('keyup',function(evt) {
    if (evt.keyCode == 27) {
       alert('Esc key pressed.');
    }
});
丑丑阿 2024-09-19 19:30:23

纯 JS,

您可以将侦听器附加到文档的 keyUp 事件。

另外,如果您想确保没有与 Esc 键一起按下任何其他键,您可以使用 ctrlKeyaltKey 的值,和shifkey

 document.addEventListener('keydown', (event) => {
        
        if (event.key === 'Escape') {
         //if esc key was not pressed in combination with ctrl or alt or shift
            const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
            if (isNotCombinedKey) {
                console.log('Escape key was pressed with out any group keys')
              
            }
        }
    });

Pure JS

you can attach a listener to keyUp event for the document.

Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.

 document.addEventListener('keydown', (event) => {
        
        if (event.key === 'Escape') {
         //if esc key was not pressed in combination with ctrl or alt or shift
            const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
            if (isNotCombinedKey) {
                console.log('Escape key was pressed with out any group keys')
              
            }
        }
    });
2024-09-19 19:30:23

检查keyCode && 其中 & keyup || 按键

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

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});
原野 2024-09-19 19:30:23

纯 JS(无 JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});

pure JS (no JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});
寂寞笑我太脆弱 2024-09-19 19:30:23

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

在此示例中,

e.preventDefault();

将禁用 ESC 按键操作。

您可以执行任何操作,例如使用以下命令隐藏 div:

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

还考虑按下 ESC 键的情况:

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

如果您想将其应用于所有人,则可以删除此 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);

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.

In this example,

e.preventDefault();

will disable the ESC key-press action.

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

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

Where the ESC key pressed is also taken into consideration:

(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.

window.addEventListener('keydown', function(e){
    if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
        e.preventDefault();
        return false;
    }
}, true);
恍梦境° 2024-09-19 19:30:23

创建函数

最好的方法是为此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!');
})

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!');
})
羁拥 2024-09-19 19:30:23

在 Firefox 78 上使用此命令(“按键”不适用于 Escape 键):

function keyPress (e)(){
  if (e.key == "Escape"){
     //do something here      
  }
document.addEventListener("keyup", keyPress);

On Firefox 78 use this ("keypress" doesn't work for Escape key):

function keyPress (e)(){
  if (e.key == "Escape"){
     //do something here      
  }
document.addEventListener("keyup", keyPress);
金橙橙 2024-09-19 19:30:23

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

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

Updated: Changed key =>键码

i think the simplest way is vanilla javascript:

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

Updated: Changed key => keyCode

静谧幽蓝 2024-09-19 19:30:23

简单的 JavaScript 代码来检测 Escape 键是否被按下

document.addEventListener("keydown",function(e){
  if(e.key === "Escape") {
    console.log("Escape key pressed")
  }
});

Simple javascript code to detect Escape key is pressed

document.addEventListener("keydown",function(e){
  if(e.key === "Escape") {
    console.log("Escape key pressed")
  }
});
找个人就嫁了吧 2024-09-19 19:30:22

注意:keyCode 已弃用,使用 key 代替。

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

代码片段:

var msg = document.getElementById('state-msg');

document.body.addEventListener('keydown', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
Press ESC key <span id="state-msg"></span>


keyCodekeypress 是已弃用。

看起来keydownkeyup可以工作。


$(document).keyup(function(e) {
     if (e.key === "Escape") { // escape key maps to keycode `27`
        // <DO YOUR WORK HERE>
    }
});

jQuery 的转义键的键码

Note: keyCode is becoming deprecated, use key instead.

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

Code Snippet:

var msg = document.getElementById('state-msg');

document.body.addEventListener('keydown', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
Press ESC key <span id="state-msg"></span>


keyCode and keypress are deprecated.

It seems keydown and keyup work.


$(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

向地狱狂奔 2024-09-19 19:30:22

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

2016 年 5 月更新

keyCode 现已被弃用,大多数现代浏览器都提供 key 属性现在,尽管您现在仍然需要后备以获得良好的浏览器支持(在编写当前版本的 Chrome 和 Safari 不支持它)。

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

The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.

Update May 2016

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).

Update September 2018
evt.key is now supported by all modern browsers.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文