通过键盘的上下左右来控制小黄人的移动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
img{
width: 200px;
height: 300px;
position: absolute;
bottom:0;
left: 50%;
margin-left: -100px;
}
</style>
<script src="./jquery-3.5.0/jquery-3.5.0.min.js"></script>
<script>
$(function(){
var $img=$(".containor>img");
$("body").keydown(function(event){
switch(event.which){
case 38:
$img.offset({left:$img.offset().left,
top:$img.offset().top-10});
break;
case 40:
$img.offset({left:$img.offset().left,
top:$img.offset().top+10});
break;
case 37:
$img.offset({left:$img.offset().left-10,
top:$img.offset().top});
break;
case 39:
$img.offset({left:$img.offset().left+10,
top:$img.offset().top});
break;
}
});
});
</script>
</head>
<body>
<div class="containor">
<img src="./one.jpg" alt="">
</div>
</body>
</html>
通过offset()函数获取偏移值,通过event.which获得按键按下的对应值并进行相应操作