【 tulaoshi.com - Web开发 】
                             
                            做web开发的时候,有时候需要根据键盘进行一些操作,例如按下Enter的时候提交表单,禁止用户输入某些特殊字符,设置快捷键等等。这时候需要找出用户按下的是那些按键,写个小程序来测试按键。
代码如下:
(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/webkaifa/)(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/webkaifa/)$(document).ready(function(){ 
var $down = $("#down"); 
var $press = $("#press"); 
var $up = $("#up"); 
$(document).keydown(function(event){ 
$down.append(String.fromCharCode(event.keyCode) + " "); 
if (event.ctrlKey) { 
alert("ctrl"); 
} 
}).keyup(function(event){ 
$up.append(String.fromCharCode(event.keyCode) + " "); 
}).keypress(function(event){ 
$press.append(String.fromCharCode(event.keyCode) + " "); 
}); 
});
方法是触发down时,把keyCode push到数组里,并删除重复元素;触发up时,用$.grep从数组中删除该keyCode。 
在任意时刻,这个数组里都保存了当前所按的按键,并且顺序是根据按键顺序排列的。 
用jQuery判断当前所按的按键方法就是用一个外部的数组保存当前按键。 
在触发keydown时,把keyCode push到数组里,并删除重复元素;触发keyup时,用$.grep从数组中删除该keyCode。 
实现代码如下:
代码如下:
(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/webkaifa/)(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/webkaifa/)当前按键:span/span 
script type="text/javascript" 
Array.prototype.unique = function () { //这个是删除重复元素用的,可惜$.unique只能处理DOM数组。 
var o = {}; 
for (var i = 0, j = 0; i  this.length; ++i) { 
if (o[this[i]] === undefined) { 
o[this[i]] = j++; 
} 
} 
this.length = 0; 
for (var key in o) { 
this[o[key]] = key; 
} 
return this; 
}; 
var $msg = $('#msg'); 
var keys = []; 
$(document).keydown(function(event){ 
keys.push(event.keyCode); 
keys.unique(); 
$msg.html(keys.join(' ')); 
}).keyup(function(event){ 
keys.push(event.keyCode); 
keys = $.grep(keys, function (n) {return n != event.keyCode;}); 
$msg.html(keys.join(' ')); 
}); 
/script