Opera 中的按键故障
我使用以下代码来检测用户在 JavaScript 中按下的按键:
$(document).bind('keydown', function (event) {
'use strict';
var keyCode = event.keyCode;
switch (keyCode) {
case '{N}':
doSomething();
break;
default:
break;
}
});
其中 doSomething
是先前定义的函数,{N}
是任何 JavaScript 字符代码。
它在每个主要浏览器中都能正常工作,但在 Opera 中,即使按住某个键,它也只会调用 doSomething
一次,而不是直到释放按键。 我可以做什么来解决这个问题?
编辑
我使用 keypress
事件而不是 keydown
(Opera 不能很好地处理)解决了这个问题。
I'm using the following code to detect users' key pressing, in JavaScript:
$(document).bind('keydown', function (event) {
'use strict';
var keyCode = event.keyCode;
switch (keyCode) {
case '{N}':
doSomething();
break;
default:
break;
}
});
Where doSomething
is a previously defined function and {N}
is any of the JavaScript Char Codes.
It works properly in every major browser, but in Opera even if a key remains pressed, it only calls doSomething
once, instead of doing it until the key is released.
What can I do to fix this?
Edit
I solved it using the keypress
event instead of keydown
(which is not well handled by Opera).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Opera 搞得一团糟,keydown 事件不重复,并且你无法阻止 Opera 中 keydown 的默认设置。了解更多http://quirksmode.org/dom/events/
Opera makes a mess, the keydown event does not repeat, and you cannot prevent the default for keydown in opera. For more http://quirksmode.org/dom/events/
这是一个已知的错误,应该(最终!)很快得到修复。简而言之,按键事件不会重复,而按键事件则会重复。如果您想要重复(并且不关心在所有浏览器中不触发按键的按键(例如大多数功能键)),那么听按键应该是一个合理的跨浏览器解决方案。
this is a known bug which should (finally!) get fixed soon. In short, keydown events are not repeated while keypress events are. Listening to keypress instead if you want repetition (and don't care about keys that do NOT fire keypress in all browsers like most function keys) should be a reasonable cross-browser solution.