Javascript(JQuery)键盘劫持问题

发布于 2024-08-29 09:54:17 字数 454 浏览 6 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2024-09-05 09:54:17

如果您想阻止按键正常的默认行为,您应该从事件处理程序中返回 false

您按下并执行某些操作的任何按键,都应该取消其默认操作。但是,请注意不要通过选择诸如 ctrl 键组合之类的内容来过度阻止,用户可能希望继续将其用作浏览器快捷方式。

$(document).keypress(function(event) {
    if (event.ctrlKey || event.altKey || event.metaKey)
        return;
    // do something with keypress
    return false;
});

(但这仍然会阻止单键操作,例如向上/向下翻页和 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.

$(document).keypress(function(event) {
    if (event.ctrlKey || event.altKey || event.metaKey)
        return;
    // do something with keypress
    return false;
});

(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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文