Javascript(JQuery)键盘劫持问题
我正在使用 javascript 制作一个打字导师程序。一切都很顺利,除了如果激活浏览器热键会破坏程序的功能。当我在 Firefox 中按下单引号时,它会触发“快速查找(仅限链接)”快捷方式,并且在所有浏览器中,当我按下空格键时,页面会向下滚动一页。除此之外一切都运行良好。这是头部的代码:
<script type="text/javascript">
$(document).ready(function() {
executeType();
});
</script>
以及我用来捕获键盘的代码(简化,但经过测试):
function executeType() {
$(document).keydown(function(event) {
alert(event.keyCode);
});
}
I'm making a typing tutor program using javascript. Everything is going well except that if activates browser hotkeys which disrupts the functionality of the program. When I press the single quote in Firefox it triggers "Quick find (links only)" short cut and in all browsers when I press space the page scrolls down a page. Everything is working fine outside of this. Here's the code in the head:
<script type="text/javascript">
$(document).ready(function() {
executeType();
});
</script>
And the code I am using to capture the keyboard (simplified, but tested):
function executeType() {
$(document).keydown(function(event) {
alert(event.keyCode);
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想阻止按键正常的默认行为,您应该从事件处理程序中
返回 false
。您按下并执行某些操作的任何按键,都应该取消其默认操作。但是,请注意不要通过选择诸如 ctrl 键组合之类的内容来过度阻止,用户可能希望继续将其用作浏览器快捷方式。
(但这仍然会阻止单键操作,例如向上/向下翻页和 F5 刷新,这不太好。您通常会查看键代码以仅检测您想要自己处理的键,让旁白:我在这里使用了 keypress 而不是 keydown,因为 Opera 不支持阻止 keydown 上的默认操作。)
If you want to stop keypresses from having their normal default behaviour, you should
return false
from the event handler.Any keypresses that you pick up and do something with, you should cancel the default action for. However, be careful not to over-block by picking up things like ctrl-key combinations which the user is likely to want to continue to use for browser shortcuts.
(This still blocks single-key actions such as page-up/down and F5-to-refresh though, which isn't great. You'd generally look at the key code to detect only the keys you wanted to handle yourself, letting the rest through. Aside: I used keypress here rather than keydown since Opera doesn't support preventing the default action on keydown.)