javascript - 使用javascript向上、下、左、右移动框

标签 javascript

所以我想通过乘以盒子然后去掉下半部分来使盒子向各个方向移动。向上和向右有效,但向下和向左无效。单击 4 个按钮中的 1 个即可调用这些功能。基本的 CSS 和 html。我该如何解决这个问题?

var box = document.getElementById("box");
var container = document.getElementById("container");
var time = document.getElementById("time");
let up2 = 1;
let right2 = 1;
let left2 = 1;
let down2 = 1;

function up() {
  box.style.height = 30 + "px";
  box.style.bottom = 30 * up2 + "px";
  up2++;
}

function right() {
  box.style.right = 30 + "px";
  box.style.left = 30 * right2 + "px";
  right2++;
}

function left() {
  box.style.left = 30 + "px";
  box.style.right = 30 * left2 + "px";
  left2++;
}

function down() {
  box.style.bottom = 30 + "px";
  box.style.top = 30 * down2 + "px";
  down2++;
}
#container {
  position: relative;
  background: purple;
  width: 400px;
  height: 400px;
}

#box {
  position: absolute;
  background: red;
  width: 30px;
  height: 30px;
  bottom: 0px;
}
<div id="container">
  <div id="box"></div>
</div>

<br />
<button class="up" onclick="up()">↑</button>

<br />

<button class="right" onclick="left()">←</button>

<button class="left" onclick="right()">→</button>

<br />

<button class="down" onclick="down()">↓</button>

最佳答案

现在剩下要做的就是将值限制为容器的大小;-)。

var box = document.getElementById("box");

function up() {
  box.style.top = (parseInt(box.style.top) - 30) + 'px';
}

function right() {
  box.style.left = (parseInt(box.style.left) + 30) + 'px';
}

function left() {
  box.style.left = (parseInt(box.style.left) - 30) + 'px';
}

function down() {
  box.style.top = (parseInt(box.style.top) + 30) + 'px';
}
#container {
  position: relative;
  background: purple;
  width: 400px;
  height: 400px;
}

#box {
  position: absolute;
  background: red;
  width: 30px;
  height: 30px;
}
<br />
<button class="up" onclick="up()">↑</button>

<br />

<button class="right" onclick="left()">←</button>

<button class="left" onclick="right()">→</button>

<br />

<button class="down" onclick="down()">↓</button>

<br/>

<div id="container">
  <div id="box" style="top: 0px; left: 0px;"></div>
</div>

关于javascript - 使用javascript向上、下、左、右移动框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58901429/

相关文章:

javascript - div的垂直定位是错误的

javascript - 如何一一获取目录下的文件链接并使用?

JavaScript:Internet Explorer 中的 document.getElementById() 错误

javascript - click 函数中的 var 变得未定义

javascript - Greasemonkey 和全局变量

javascript - 为什么在 Vue js 中尝试从 firebase 检索 token 时出现错误?

javascript - 将 html2pdf 生成的 pdf 发送回服务器

javascript - 在 Bootstrap 模态中暂停 Vzaar 视频

javascript - 为什么 string.split() 对于正则表达式的行为不同?

javascript - Emacs 有问题的 JavaScript 缩进