1.键盘控制方块在固定区域内移动
//首先根据题目要求我们可以知道具体步骤如下操作:
//1.先去放两个盒子一大一小,并且获取键盘所对应的值
//2.小盒子通过设置绝对定位,键盘按下在规定区域内移动,对此补充一个知识点:
//可以利用offsetLeft和offsetTop获取移动的小箱子的当前位置距离左侧和上侧的数值:具体代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>移动色块</title>
<style>
.box {
width: 500px;
height: 500px;
background-color: pink;
position: relative;
}
.small {
width: 50px;
height: 50px;
background-color: skyblue;
position: absolute;
}
</style>
</head>
<body>
<div class="box">
<div class="small"></div>
</div>
<button>上</button>
<button>下</button>
<button>左</button>
<button>右</button>
</body>
<script>
var box = document.querySelector(".box");
var small = document.querySelector(".small")
document.onkeydown = function (e) {
console.log(e.keyCode);
switch (e.keyCode) {
case 37:
if (small.offsetLeft != 0) {
small.style.left = small.offsetLeft - 50 + 'px';
}
break;
case 38:
if (small.offsetTop != 0) {
small.style.top = small.offsetTop - 50 + 'px';
}
break;
case 39:
if (small.offsetLeft != 450) {
small.style.left = small.offsetLeft + 50 + 'px';
}
break;
case 40:
if (small.offsetTop != 450)
small.style.top = small.offsetTop + 50 + 'px';
break;
default:
break;
}
}
</script>
</html>