简体   繁体   English

在按键上执行JavaScript

[英]Execute JavaScript on Key Press

I am trying to add a script to my website that is only executed on key press, using JavaScript to handle the event. 我正在尝试将脚本添加到我的网站,该脚本仅在按键时执行,并使用JavaScript处理事件。 They specific key to be pressed is the one located below the "esc" key; 他们要按下的特定键是“ esc”键下面的那个; the "`" key. “`”键。 I have found that the code for this key is 192, where the "Enter" key is 13 if that makes sense. 我发现此键的代码为192,如果可以的话,其中“ Enter”键为13。

Here is the code I currently have & I don't understand why it isn't working: 这是我目前拥有的代码,我不明白为什么它不起作用:

  $(document).keypress(function(e) {
    if(e.which == 192) {
        //CODE I WANT TO EXECUTE GOES HERE
  }
})

Please help! 请帮忙! I would use HTML but it is for a single .js file included on different pages around different sites. 我会使用HTML,但这是针对单个.js文件的,该文件包含在不同站点周围的不同页面上。 Also, I have read that there is code that only does this while in focus and I need it to work anywhere on the page. 另外,我已经读到有一些代码只有在焦点对准时才能执行此操作,并且我需要它可以在页面上的任何地方工作。

27 is the code for the escape key. 27是转义键的代码。 You can find the hex code for all the characters in this link ( http://asciitable.com/ ). 您可以在此链接( http://asciitable.com/ )中找到所有字符的十六进制代码。 Try this, 尝试这个,

$(document).keyup(function(e) {
    if(e.which === 27 || e.keyCode === 27) {
        //CODE I WANT TO EXECUTE GOES HERE
    }
});

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

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