我很好奇我如何用下面的jQuery插件代码即时编写这个问题的底部,可以实现关键的组合。它是如何工作的,到目前为止是它允许用户只需通过做一个正常的jQuery像语法创建关键命令和键盘命令提供了一个事件,像这样:使用jQuery/JavaScript做关键组合
$(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虚假和的keydown设置VAR真实和检查如果var是当你按下其他键时是真的),但是当你不知道要按什么键以及有多少键时,我不知道该怎么做。我如何添加此支持?如果他们想要,我希望能够让他们做像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);
您正在全局范围内定义'x'。 – 2010-11-04 23:42:41
我认为范围问题可以通过像这样定义x和y来解决:var x =''; var y =''; ? – sebnitu 2010-11-05 01:13:31
或者更好的是,我们可以通过在for语句中添加var来定义它们? for(var x in keySplit){... – sebnitu 2010-11-05 01:18:34