简体   繁体   English

如何添加事件以按“ Esc”键?

[英]How do I add event to press 'Esc'?

<input type="text" id= 'input'>

let input = document.getElementById('input');
    //add event listener to keydown event    
    input.addEventListener('keydown',(e)=> {
        console.log(e.key);
      //check the key is 'Escape'
        if( e.key === 'Escape') {
            input.select();} 
        });

when I press 'Esc', it didn't work it only blur, don't select what I type in the input element. 当我按“ Esc”键时,它不起作用,只能模糊,不要选择我在输入元素中输入的内容。 Where did I make mistake? 我在哪里弄错了?

for pure js 对于纯js

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

for jquery 对于jQuery

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

Your code is running fine. 您的代码运行良好。 Check it on JS Bin. 在JS Bin上检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM