为什么'keydown'事件就像'keypress'事件一样? [英] Why 'keydown' event works like 'keypress' event?
问题描述
当我按住按钮时,下一个示例代码多次输出'keydown'消息。文档说只需按一下按钮即可发生一次keydown事件。因此,keydown事件的作用类似于下一个示例中的按键事件。
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>
我在Windows,Firefox 19.0.2和Google Chrome 25.0.1364.152上进行了测试。我还创建了一个小提琴(问题可以复制)。重现问题的JQuery版本:1.8.2,1.9.1。
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.
更新。
我做了意识到这个问题:如何在JavaScript中避免自动重复的keydown事件? 。
I did realize the problem: How can I avoid autorepeated keydown events in JavaScript?.
推荐答案
keydown
按下键时发生事件,紧接着是keypress
事件。然后在释放密钥时生成keyup
事件。
The
keydown
event occurs when the key is pressed, followed immediately by thekeypress
event. Then thekeyup
event is generated when the key is released.
为了理解<$ c之间的区别$ c> keydown 和 keypress
,了解字符和键之间的区别很有用。 键是计算机键盘上的物理按钮,而字符是通过按下按钮键入的符号。理论上, keydown
和 keyup
事件表示按下或释放的键,而按键
event表示正在键入的字符。所有浏览器的理论实现都不相同。
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.
这篇关于为什么'keydown'事件就像'keypress'事件一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!