问题描述
如何捕获按键,例如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>");
});
这篇关于在不在页面上放置输入元素的情况下捕获按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!