效果:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>作业6-键盘事件</title>
<script src="utility.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
border: 0px solid #000000;
}
#bd{
background: url(img-4.jpg);
background-repeat: no-repeat;
border: 0px solid;
}
#b-box{
width: 900px;
height: 724px;
position: relative;
}
#img0{
width: 40px;
position: absolute;
bottom: 10px;
left: 85px;
}
</style>
</head>
<body id="bd" onkeydown="move(event)">
<script type="text/javascript">
function move(e){
if(e.key == 'w' || e.key == 'W')
$("img0").style.top = $("img0").offsetTop - 10 + "px";
if(e.key == 'a' || e.key == 'A')
$("img0").style.left = $("img0").offsetLeft - 10 + "px";
if(e.key == 's' || e.key == 'S')
$("img0").style.top = $("img0").offsetTop + 10 + "px";
if(e.key == 'd' || e.key == 'D')
$("img0").style.left = $("img0").offsetLeft + 10 + "px";
}
</script>
<div id="b-box">
<img src="img-3.jpg" alt="hero.jpg" id="img0"/>
</div>
</body>
</html>
其中用到的utility.js:
function $(id){
return document.getElementById(id);
}
function l(a){
console.log(a);
}
DOM练习文件:
https://download.csdn.net/download/cc2855816075/80848641
注意:
1、键盘的事件设在body上。 2、offsetLeft元素偏移量,注意写法!+“px”,把它设成字符串,格式同CSS。 $(“img0”).style.top = $(“img0”).offsetTop - 10 + “px”;
|