键盘事件对象:即每一个按键。值得注意的是:我们在按键的时候,keydown 支持特殊按键,但是不区分大小写,而keypress不支持特殊按键,但是区分大小写。
获取事件对象:
document.onkeydown = function(ev){
// 获取事件对象,可以使用window.event,注意:在火狐获取不到
console.log(window.event);
// 在火狐要通过参数获取
console.log(ev);
// 兼容性的写法
var evObj = window.event || ev;
console.log(evObj.keyCode);
// 如何判断是否按了组合键
if(evObj.keyCode==67 && evObj.metaKey){
console.log("按了command+c");
}
}
实例小测试:用方向键控制元素移动
var redDiv = document.getElementsByClassName('redDiv')[0];
var rightDown = false;
var leftDown = false;
var topDown = false;
var botDown = false;
document.onkeydown = function(ev){
var evObj = window.event ||ev;
if (ev.keyCode ==39) {
// redDiv.style.left = redDiv.offsetLeft + 5 + "px";
rightDown = true;
}
if (ev.keyCode ==38) {
topDown = true;
}
if (ev.keyCode ==37) {
leftDown = true;
}
if (ev.keyCode ==40) {
botDown = true;
}
}
document.onkeyup = function(ev){
var evObj = window.event ||ev;
if (ev.keyCode ==39) {
rightDown = false;
}
if (ev.keyCode ==38) {
topDown = false;
}
if (ev.keyCode ==37) {
leftDown = false;
}
if (ev.keyCode ==40) {
botDown = false;
}
}
setInterval(function(){
if (rightDown) {
redDiv.style.left = redDiv.offsetLeft+5+"px";
}
if (topDown) {
redDiv.style.top = redDiv.offsetTop-5+"px";
}
if (botDown) {
redDiv.style.top = redDiv.offsetTop+5+"px";
}
if (leftDown) {
redDiv.style.left = redDiv.offsetLeft-5+"px";
}
},20);
方法二:(优化写法)
var boolArr = [false,false,false,false];
document.onkeydown = function(ev){
var evObj = window.event ||ev;
boolArr[ev.keyCode - 37] = true;
}
document.onkeyup = function(ev){
var evObj = window.event ||ev;
boolArr[ev.keyCode - 37] = false;
}
setInterval(function(){
var speed = 5;
var leftSpeed = boolArr[0]* -speed + boolArr[2]*speed;
var topSpeed = boolArr[1]* -speed + boolArr[3]*speed;
redDiv.style.left = redDiv.offsetLeft+leftSpeed+"px";
redDiv.style.top = redDiv.offsetTop+topSpeed+"px";
},10);