javascript - JavaScript 盒子游戏 - 内部 div 超出外部 div 边界
问题描述
我无法让内部 div 在移动视图中正确地停留在外部 div 的边界内。请通过检查此代码有什么问题来帮助我。我是 JavaScript 新手。
HTML
<div class="GameArea">
<div class="message">
<h4>How to Play</h4>
<div>
Just click on the blue box to score points!
</div>
X:<span class="x">0</span>
Y:<span class="y">0</span>
<br>
Score <span class="score">0</span>
</div>
<div class="output">
<div><h4 class="text-center banner">Let's start!</h4></div>
</div>
</div>
JS
function move() {
let speed = Math.random() * 10;
const box = document.querySelector(".box");
let bounds = output.getBoundingClientRect();
box.steps--;
if (box.steps < 0) {
box.direction = Math.floor(Math.random() * 4);
box.steps = Math.random() * 20;
}
if (box.direction == 0 && box.x < bounds.right - 440) {
box.x += speed;
}
if (box.direction == 1 && box.x > bounds.left) {
box.x -= speed;
}
if (box.direction == 2 && box.y < bounds.bottom - 165) {
box.y += speed;
}
if (box.direction == 3 && box.y > bounds.top) {
box.y -= speed;
}
box.style.top = box.y + "px";
box.style.left = box.x + "px";
window.requestAnimationFrame(move);
}
解决方案
推荐阅读
- python - Django Teamplate 选项卡不显示
- react-native - 错误:已为此容器注册了另一个导航器。您可能在单个“NavigationContainer”或“Screen”下有多个导航器
- asp.net-core - Serilog dotnet core function app 和 sql sink
- javascript - WordPress:JS 已加载,但其中的功能不起作用
- linux - 如何在 kali linux 上安装 pip2 和 pip3?
- excel - Azure 逻辑应用获取目标工作表行值
- spring - 好奇docker-compose和dockerfile的使用
- image - 将 html 转换为 odt 或 docx 时嵌入图像
- sql - Oracle - 如何处理函数错误并返回 null
- node.js - Node.js 和 Oracle DB 选择查询在行中获取空数组