开发者

Javascript event triggered by pressing space

I am trying to get an event to trigger when I a开发者_JAVA百科m on a page and press space, but I can't figure it out. Currently I am trying to use jQuery to accomplish a satisfying result.

I have tried using keydown, keyup and keypress, but it seems that you can only use it if you are actually inputting something to a form or field.

What I want is to trigger an alert when space is pressed.


These events bubble up, so if you're trying to trigger the event wherever your focus is (ie. not in an input), just bind a handler on window:

$(window).keypress(function (e) {
  if (e.key === ' ' || e.key === 'Spacebar') {
    // ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
    e.preventDefault()
    console.log('Space pressed')
  }
})

Also see the list of all .key values.


Try this:

$('input:text').keypress(function(e) {
    if (e.keyCode == 0 || e.keyCode == 32) // `0` works in mozilla and `32` in other browsers
       console.log('space pressed');
});


Try to bind your key event listener to the jQuery $(document) object;

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $(document).keydown(function(e) {
          if (e.keyCode == '32') {
            alert('space');
          }
        });
      });
    </script>
  </head>
  <body>
  </body>
</html>


This code can be used:

$(window).keypress(function(e) {
  if (e.keyCode == 0 || e.keyCode == 32) {
    console.log('Space pressed');
  }
});


Explaination:
The $(window).keypress(function(e) waits for the user to press any key and stores the data of the key pressed in the argument 'e'.
Then if (e.keyCode == 0 || e.keyCode == 32) checks if the code of the key pressed is equal to the code of spacebar, that is 0 or 32. If this returns false then any other key is pressed and the code ends.

Some commonly used keycodes:

  • backspace:8
  • tab:9
  • enter:13
  • shift:16
  • ctrl:17
  • alt:18
  • caps lock:20
  • escape:27
  • (space):32
  • 0-9:48-57
  • a-z:65-90
  • numpad0-numpad9:96-105
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜