Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - 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?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...