通过键盘移动红色方块
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>键盘移动div</title>
<script>
window.onload = function () {
var box = document.getElementById('box');
document.onkeydown = function (event) {
event = event || window.event;
/*
左 37
右 39
上 38
下 40
*/
var speed=10;
// ctrl 和方向键按住才有效果
if(event.ctrlKey){
speed=50;
}
switch (event.keyCode) {
case 37:
box.style.left = box.offsetLeft - speed + 'px';
break;
case 38:
box.style.top = box.offsetTop - speed+ 'px';
break;
case 39:
box.style.left = box.offsetLeft + speed+ 'px';
break;
case 40:
box.style.top = box.offsetTop + speed + 'px';
break;
}
};
};
</script>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>