How do I capture keystrokes on the web?

非 Y 不嫁゛ 提交于 2019-11-29 17:59:35

Sure, the only way to do this would be through JavaScript, and you'd do so like this:

window.onload = function() {
   document.getElementsByTagName('body')[0].onkeyup = function(e) { 
      var ev = e || event;
      if(ev.keyCode == 70) {//&& ev.ctrlKey) {
         //do something...
      }
   }
};

To find out the specific key code you want, see this article: http://www.webonweboff.com/tips/js/event_key_codes.aspx

jsFiddle example

You're looking for the javascript events associated with key presses. There are some annoying browser incompatibilities here, so you'll be best off using a JS library like jQuery, where you can use the jQuery keypress() method, but you can get the data you want from the javascript onkeypress event.

Using jQuery:

You can do it using jQuery Keydown

Nice article on capturing different key events:

Working with Events in jQuery

EDIT:

JavaScript

Here are nice articles to do this in javascript with nice DEMO:

You are better off capturing all keys on the window rather than capturing key strokes on a specific element like other answers referred to.

so using native javascript:

window.onload = function (){
 eventHandler = function (e){
    if (e.keyCode == 70 && e.ctrlKey)
    {
      //do stuff
      //console.log(e);
    }
  }

  window.addEventListener('keydown', eventHandler, false);
}

using JQuery:

$(document).ready(function(){
  $(window).keydown(function (e) {
    if (e.keyCode == 70 && e.ctrlKey)
    {
        //do stuff
    }

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