if (keyCode == 38) { top -= 10; } if (keyCode == 40) { top += 10; } if (keyCode == 37) { left -= 10; } if (keyCode == 39) { left += 10; } if (left < 0) { left = 0; } if(top<0){ top=0; } if (top > maxTop) { top = maxTop; } if (left > maxLeft) { left = maxLeft; } oBox1.style.cssText = `left:${left}px;top:${top}px`; }, 50); }; </script> </body> </html>
移动的盒子
<!--
* @Author: your name
* @Date: 2021-04-08 14:30:47
* @LastEditTime: 2021-04-08 19:16:21
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \二阶段\4.8\陈志宝\移动的盒子.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 800px;
height: 500px;
border: 10px solid black;
margin: auto;
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
}
.box1 {
width: 30px;
height: 30px;
background-color: #f00;
border: 10px solid black;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
<script>
var oBox = document.querySelector(".box");
var oBox1 = document.querySelector(".box1");
var maxTop = oBox.clientHeight - oBox1.offsetHeight;
var maxLeft = oBox.clientWidth - oBox1.offsetWidth;
var t;
document.onkeydown = function (e) {
var e = event || e;
var keyCode = e.keyCode || e.which;
console.log(keyCode);
clearInterval(t);
t = setInterval(function () {
//定义上下的方向的移动距离,是通过offsetLeft是具有定位元素的祖先元素获取的
var left = oBox1.offsetLeft;
var top = oBox1.offsetTop;
if (keyCode == 38) { top -= 10; } if (keyCode == 40) { top += 10; } if (keyCode == 37) { left -= 10; } if (keyCode == 39) { left += 10; } if (left < 0) { left = 0; } if(top<0){ top=0; } if (top > maxTop) { top = maxTop; } if (left > maxLeft) { left = maxLeft; } oBox1.style.cssText = `left:${left}px;top:${top}px`; }, 50); }; </script> </body> </html>
if (keyCode == 38) { top -= 10; } if (keyCode == 40) { top += 10; } if (keyCode == 37) { left -= 10; } if (keyCode == 39) { left += 10; } if (left < 0) { left = 0; } if(top<0){ top=0; } if (top > maxTop) { top = maxTop; } if (left > maxLeft) { left = maxLeft; } oBox1.style.cssText = `left:${left}px;top:${top}px`; }, 50); }; </script> </body> </html>