所以我想通过乘以盒子然后去掉下半部分来使盒子向各个方向移动。向上和向右有效,但向下和向左无效。单击 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/