为什么 keypress 不处理删除键和退格键
我问这个不是因为我需要解决方法。我有一个工作正常,但我想知道为什么不行。这是 Javascript 中的错误(还是 JQuery,因为我使用的是 JQuery .keypress
处理程序),或者是否有特定原因导致这种情况?
I'm not asking this because I need a work-a-around. I have one that works fine, but I want to know WHY it doesn't. Is this bug in Javascript (or JQuery because I was using the JQuery .keypress
handler) or is there a specific reason why this is so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
keypress
事件旨在处理用户键入的字符,而不是检测键盘活动,并且删除和退格键不会生成字符。有些浏览器在某种程度上模糊了这条线,但一般原则是,keyup
和keydown
事件用于检测按下的任何键,并告诉您在时是哪个键。 >keypress
用于检测正在键入的实际字符。The
keypress
event is designed for handling a character typed by the user rather than detecting keyboard activity and the delete and backspace keys do not generate characters. Some browsers blur this line somewhat but the general principle is that thekeyup
andkeydown
events are there to detect any key being pressed and telling you about which key it is whilekeypress
is for detecting an actual character being typed.简短的回答是,并非所有浏览器中的所有按键类型都会触发 onkeypress 事件。检查您的浏览器的手册。
为什么?
可能不是一个全面的答案,但考虑一下 Shift,相对于其他键,它何时按下以及何时上升是很重要的。不同的键盘硬件具有不同的按键翻转特性,您可能想详细了解这些特性。
The short answer is that the onkeypress event is not fired for all key types in all browsers. Check the manual for your browser.
Why?
Probably not a comprehensive answer, but consider Shift, when it goes down and when it comes up relative to other keys is significant. And different keyboard hardware has different key rollover characteristics which you might want to know about in detail.