Execute onclick of ESC Key

房东的猫 提交于 2019-12-05 13:38:15

问题


Briefly, my problem is that I would like to execute the effect of Esc button by a line of javascript, for example execute an effect onclick of the Esc button. How can I do It ?

[ What I have is an upload in a jQuery box, so I would like that when the upload will finish, the escape function will be executed automatically to close the box]


回答1:


I know it's an old question. However if somebody lands in here on search, it may help:

First, trigger the event on desired element (or document),

$('a[name=close]').click(function(){
    var e = jQuery.Event("keyup"); // or keypress/keydown
    e.keyCode = 27; // for Esc
    $(document).trigger(e); // trigger it on document
});

And then, have a keyup listener on document:

// Esc key action
$(document).keyup(function(e) {
    if (e.keyCode == 27) { // Esc
        window.close(); // or whatever you want
    }
});



回答2:


This code works for me

$(document).keyup(function(e) {     
    if(e.keyCode== 27) {
        alert('Esc key is press');  
    } 
});


来源:https://stackoverflow.com/questions/6415299/execute-onclick-of-esc-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!