// 1、键盘执行函数,输出键码
document.onkeydown = function (e) {
console.log(e.keyCode); // 键码
}
// 2、键盘上下左右,输出键码
document.onkeydown = function (e) {
let code = e.keyCode;
switch (code) {
case 37: console.log('左'); break;
case 38: console.log('上'); break;
case 39: console.log('右'); break;
case 40: console.log('下'); break;
}
}
// 3、移动盒子(俄罗斯方块)
var box = document.querySelector('.box');
console.log(box.offsetLeft); // 向左偏移量
console.log(box.offsetTop); // 向上偏移量
document.onkeydown = function (e) {
let code = e.keyCode;
switch (code) {
// 移动盒子,上下左右
case 37: box.style.left = box.offsetLeft - 5 + 'px'; break;
case 38: box.style.top = box.offsetTop - 5 + 'px'; break;
case 39: box.style.left = box.offsetLeft + 5 + 'px'; break;
case 40: box.style.top = box.offsetTop + 5 + 'px'; break;
}
}