简体   繁体   中英

Why 'keydown' event works like 'keypress' event?

The next sample code outputs 'keydown' message many times while I hold a button down. The docs says that the keydown event happens once for one push of the button. So, the keydown event works like the keypress event in the next example.

<!DOCTYPE HTML>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title></title>

  <script type='text/javascript' src='jquery.js'></script>
  <script type='text/javascript'>
    function onLoad()
    {
        $( '#text' ).on( 'keydown', function() { console.info( 'keydown' ) } ); 
    }   
  </script>

  </head>
  <body onload='onLoad()'>
     <input type='text' id='text'>

  </body>
</html>

I tested it on Windows, Firefox 19.0.2 and Google Chrome 25.0.1364.152. Also I created a fiddle (the problem can be reproduced). JQuery versions for which problem is reproduced: 1.8.2, 1.9.1.

Update.

I did realize the problem: How can I avoid autorepeated keydown events in JavaScript? .

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

In order to understand the difference between keydown and keypress , it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

Key events occur in the following order:

  1. KeyDown
  2. KeyPress
  3. KeyUp

Are these events available on the Window, Document, Form, focusable elements
Test Page

按下键时会发生keydown事件,紧接着是按下按键事件。

i have answer here, following me slowly: keydown : working when you start typing key or start to change something and keydown give you one result for one press but give you the result before the last one not last result. keyup : working when you stop typing a key or go back (change something like remove character) and it's give give you last result. keypress : working when you start typing key but not start to change something and keydpress give you one result for one press but give you the result before the last ,which (lastResult - 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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