在不在页面上放置输入元素的情况下捕获按键? [英] Capture key press without placing an input element on the page?

查看:110
本文介绍了在不在页面上放置输入元素的情况下捕获按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何捕获按键,例如Ctrl + Z,而不在JavaScript中在页面上放置输入元素?似乎在IE中,keypress和keyup事件只能绑定到输入元素(输入框,textareas等)

How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input elements (input boxes, textareas, etc)

推荐答案

jQuery还有一个非常好的实现,非常容易使用。以下是跨浏览器实现此功能的方法:

jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:

$(document).keypress(function(e){
    var checkWebkitandIE=(e.which==26 ? 1 : 0);
    var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);

    if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});

在IE7,Firefox 3.6.3& Chrome 4.1.249.1064

Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064

另一种方法是使用keydown事件并跟踪event.keyCode。但是,由于jQuery使用event.which规范化keyCode和charCode,因此他们的规范建议在各种情况下使用event.which:

Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:

$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
    $("body").append("<p>ctrl+z detected!</p>");
});

这篇关于在不在页面上放置输入元素的情况下捕获按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆