<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style type="text/css">
.container{
width: 200px;
height: 360px;
background-color: antiquewhite;
position: relative;
}
.actvity_model{
width: 20px;
height: 20px;
background-color: cornflowerblue;
border: .3px solid #eee;
box-sizing: border-box;
position: absolute;
}
</style>
</head>
<body onload="init();">
<!-- 背景容器 -->
<div class="container">
<!-- 块元素 -->
<div class="actvity_model"></div>
</div>
<script>
//创建一个常量控制步长
const STEP = 20;
//入口方法
function init(){
onKeyDown();
}
//监听用户键盘事件
function onKeyDown(){
document.onkeydown = function(evnet){
switch(event.keyCode){
case 38:
console.log("上");
move(0,-1);
break;
case 39:
console.log("右");
move(1,0);
break;
case 40:
console.log("下");
move(0,1);
break;
case 37:
console.log("左");
move(-1,0);
break;
}
}
}
//控制块元素移动
function move(x,y){
var actvityModelEle = document.querySelector(".actvity_model");
actvityModelEle.style.top = parseInt(actvityModelEle.style.top || 0) + y * STEP + "px";
actvityModelEle.style.left = parseInt(actvityModelEle.style.left || 0) + x * STEP + "px";
}
</script>
</body>
</html>