小demo:通过按键控制小黄人的移动

通过键盘的上下左右来控制小黄人的移动

<!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获得按键按下的对应值并进行相应操作

猜你喜欢

转载自blog.csdn.net/weixin_43797908/article/details/107320909
今日推荐