Javascript 如何使用javascript或jquery禁用html页面中的esc键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6729249/
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 22:57:11  来源:igfitidea点击:

How to disable esc key in html page using javascript or jquery

javascriptjqueryjquery-uijquery-ui-dialog

提问by Royal Pinto

I want to disable the ESC key in an HTML page. How can I do this?

我想在 HTML 页面中禁用 ESC 键。我怎样才能做到这一点?

I have a form which is appearing as jQuery UI Dialog. Here if I click the ESC key, the form will close. I want to disable that.

我有一个显示为 jQuery UI 对话框的表单。在这里,如果我单击 ESC 键,表单将关闭。我想禁用它。

回答by álvaro González

Browsers (Firefox, Chrome...) normally bind the Esckey to the "stop loading current page" action. Any other behaviour needs to be specifically coded with JavaScript.

浏览器(FirefoxChrome...)通常将Esc键绑定到“停止加载当前页面”操作。任何其他行为都需要用 JavaScript 专门编码。

The jQuery UI Dialog has a closeOnEscapesetting. Just set it to false:

jQuery UI 对话框有一个closeOnEscape设置。只需将其设置为false

  • Initialize a dialog with the closeOnEscape option specified:

    $( ".selector" ).dialog({ closeOnEscape: false });
    
  • Get or set the closeOnEscape option, after init:

    //getter
    var closeOnEscape = $( ".selector" ).dialog( "option", "closeOnEscape" );
    //setter
    $( ".selector" ).dialog( "option", "closeOnEscape", false );
    
  • 使用指定的 closeOnEscape 选项初始化对话框:

    $( ".selector" ).dialog({ closeOnEscape: false });
    
  • 在 init 之后获取或设置 closeOnEscape 选项:

    //getter
    var closeOnEscape = $( ".selector" ).dialog( "option", "closeOnEscape" );
    //setter
    $( ".selector" ).dialog( "option", "closeOnEscape", false );
    

回答by Sinetheta

$(document).keydown(function(e) {
    if (e.keyCode == 27) return false;
});

*thanks Johan

*感谢约翰

回答by Femi

The best way to do this is to figure out which dialog library you are using (colorbox? jquery ui? shadowbox) and disable the esckey (for example, in Colorboxyou can set the escKeyoption to false).

最好的方法是找出您使用的是哪个对话框库(colorbox?jquery ui?shadowbox)并禁用该esc键(例如,在Colorbox 中您可以将escKey选项设置为 false)。