JavaScript經典案例:鍵盤控制元素移動

宛如秋兮WanAkiko.發表於2020-11-25

效果展示:
在這裡插入圖片描述
CSS程式碼:

<style type="text/css">
	#box {
		position: absolute;
		width: 100px;
		height: 100px;
		line-height: 100px;
		text-align: center;
		background-color: #FFEB3B;
	}
</style>

HTML程式碼:

<div id="box">Ctrl加速</div>

JavaScript程式碼:

<script type="text/javascript">
	window.onload = function() {
		var box = document.getElementById("box");
		var speed = 10; // 定義移動速度
		if (event.ctrlKey) {
			speed = 50; // 按下Ctrl加速
		}
		document.onkeydown = function(event) {
			event = event || window.event;
			switch (event.keyCode) {
				case 38: // 上
					box.style.top = box.offsetTop - speed + "px"
					break;
				case 40: // 下
					box.style.top = box.offsetTop + speed + "px"
					break;
				case 37: // 左
					box.style.left = box.offsetLeft - speed + "px"
					break;
				case 39: // 右
					box.style.left = box.offsetLeft + speed + "px"
					break;
			}
		}
	}
</script>

相關文章