【问题标题】:How do I add event to press 'Esc'?如何添加事件以按“Esc”?
【发布时间】:2018-12-13 05:19:06
【问题描述】:

<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();} 
        });

当我按“Esc”时,它不起作用,它只会模糊,不要选择我的 输入输入元素。我哪里弄错了?

【问题讨论】:

标签: javascript


【解决方案1】:

纯js

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

jquery

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

【讨论】:

    【解决方案2】:

    您的代码运行良好。在 JS Bin 上查看。

    【讨论】:

    • @jackpetton 您提供的 codepen 链接适用于 chrome 和 firefox
    • 杰克,你应该换个浏览器试试看。它在 codepen 中对我来说工作正常。
    • @NishantSolanki 为什么它在我的电脑上不起作用?
    • @DeveshN。提高声望的方法有很多。请参考此链接meta.stackexchange.com/questions/17204/…
    • @jackpetton 你用的是哪台电脑和浏览器?还有console.log(e.key) 在控制台中显示什么?
    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 2013-12-13
    • 2021-01-16
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多