【前端 HTML+CSS+JavaScript(JS)】DOM练习-onkeydown键盘事件-用wasd移动图片的位置 带注释/总结

  • Post author:
  • Post category:java

效果:

在这里插入图片描述

代码:

<!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上★★★ -->
	<body id="bd" onkeydown="move(event)">
		
		<script type="text/javascript">
		//keyCode   w: 87 s: 83 a: 65 d: 68
			function move(e){
				// l($("img0").offsetLeft);
				if(e.key == 'w' || e.key == 'W')
					//★★★offsetLeft元素偏移量,注意写法!+"px",把它设成字符串,格式同CSS★★★
					$("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”;


版权声明:本文为cc2855816075原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。