<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>键盘控制小球的移动</title>
<style type="text/css">
div{
/* background: orange;*/
width: 100px;
height: 100px;
padding: 30px;
border-radius: 200px;
position: absolute;
background-image: url(pic/sc16.png);
}
</style>
</head>
<body>
<div id="ball" style="top:50px;left: 50px"></div>
<script>
var key={
W:87,
S:83,
A:65,
D:68,
}
function keymove(e){
var ball=document.getElementById('ball');
var top=parseInt(ball.style.top);
var left=parseInt(ball.style.left);
// alert(top+50+'px');
switch(e.keyCode){
case key.W:
ball.style.top=top-50+'px';
break;
case key.S:
ball.style.top=top+50+'px';
break;
case key.A:
ball.style.left=left-50+'px';
break;
case key.D:
ball.style.left=left+50+'px';
break;
}
}
document.onkeydown= keymove;
</script>
</body>
</html>