asdw键移动图片.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{padding: 0;margin: 0;}
#box{
width: 200px;height: 200px;position: absolute;top: 100px;left: 100px;
}
</style>
</head>
<body>
<div id="box">
<img src="img/Game figure.jpg"/>
</div>
<script type="text/javascript">
//ASCII码 上87下83左65右68
var o=document.getElementById('box');
document.onkeydown=function (e)
{
e=e||window.event;
//console.log(e.keyCode);//得到上下左右四个按键码
//判断按键
if (e.keyCode==87)
{
var preTop=window.getComputedStyle(o,null).top;//上
preTop=parseInt(preTop);//去单位
//在原来图片的位置减去10px
o.style.top=preTop-10+'px';
}else if (e.keyCode==83)
{
var preTop=window.getComputedStyle(o,null).top;//下
preTop=parseInt(preTop);
o.style.top=preTop+10+'px';
}else if (e.keyCode==65)
{
var preLeft=window.getComputedStyle(o,null).left;//左
preLeft=parseInt(preLeft);
o.style.left=preLeft-10+'px';
}else if (e.keyCode==68)
{
var preLeft=window.getComputedStyle(o,null).left;//右
preLeft=parseInt(preLeft);
o.style.left=preLeft+10+'px';
}else
{
alert('按键点击错误,请点击有效按键!');
}
}
</script>
</body>
</html>