我很好奇,我如何使用我在这个问题底部编写的以下 jQuery 插件代码来实现组合键。到目前为止,它是如何工作的,它允许用户简单地通过执行类似 jQuery 的语法来创建键命令,并为键命令提供一个事件,如下所示:
$(window).jkey('a',function(){
alert('you pressed the a key!');
});
或
$(window).jkey('b c d',function(){
alert('you pressed either the b, c, or d key!');
});
最后我想要的是能够做到,但想不通:
$(window).jkey('alt+n',function(){
alert('you pressed alt+n!');
});
我知道如何在插件之外执行此操作(在 keyup 上设置 var false,在 keydown 上设置 var true 并在按下另一个键时检查 var 是否为 true),但我不知道如何当您不知道要按下哪些键以及按下多少键时,请执行此操作。如何添加此支持?如果他们愿意,我希望能够允许他们执行 alt+shift+a
或 a+s+d+f
之类的操作。我只是无法理解如何实现这一点。有任何想法吗?
我将把它作为一个开源插件发布,我很乐意给任何给我权利的人,工作,在博客文章和它自己的代码中回答一些功劳。提前致谢!
(function($) {
$.fn.jkey = function(keyCombo,callback) {
if(keyCombo.indexOf(' ') > -1){ //If multiple keys are selected
var keySplit = keyCombo.split(' ');
}
else{ //Else just store this single key
var keySplit = [keyCombo];
}
for(x in keySplit){ //For each key in the array...
if(keySplit[x].indexOf('+') > -1){
//Key selection by user is a key combo... what now?
}
else{
//Otherwise, it's just a normal, single key command
}
switch(keySplit[x]){
case 'a':
keySplit[x] = 65;
break;
case 'b':
keySplit[x] = 66;
break;
case 'c':
keySplit[x] = 67;
break;
//And so on for all the rest of the keys
}
}
return this.each(function() {
$this = $(this);
$this.keydown(function(e){
if($.inArray(e.keyCode, keySplit) > -1){ //If the key the user pressed is matched with any key the developer set a key code with...
if(typeof callback == 'function'){ //and they provided a callback function
callback(); //trigger call back and...
e.preventDefault(); //cancel the normal
}
}
});
});
}
})(jQuery);
最佳答案
使用 keypress 而不是 keyup/keydown 因为后两者不能准确地显示键码( reference ,见最后一段)。在这种情况下,您可以引用事件对象的 altKey
ctrlKey
和 shiftKey
bool 属性...
$(document).keypress(function(e) {
var key = String.fromCharCode(e.which);
var alt = e.altKey;
var ctrl = e.ctrlKey
var shift = e.shiftKey;
alert("Key:" + key + "\nAlt:" + alt + "\nCtrl:" + ctrl + "\nShift:" + shift);
});
此外,您可以使用 String.fromCharCode
将键码转换为实际字母。
除了与 Ctrl、Alt 和 Shift 组合之外,您不能捕获多个键。您根本无法在单个事件中做到这一点。因此,请将 a+s+d+f
想法扔到窗外。
注意:显然浏览器使用了某些组合键。例如,Alt + F 通常会调出 Windows 中的文件菜单。 Ctrl + N 通常会启动一个新窗口/选项卡。不要尝试覆盖任何这些组合。
这是一个 live demo为了您的测试乐趣。
关于javascript - 使用 jQuery/JavaScript 进行组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4074645/