我是JavaScript新手,所以我遇到了一些困难。我想用箭头键在左边,上边,右边和下边的另一个更大的div中移动一个小div。我有下面的代码,但它无法正常工作。
HTML和CSS
<div id="rectangle">
<div id="square"></div>
</div>
#rectangle {
width: 320px;
height: 200px;
border: 1px solid;
margin: auto;
position: relative;
}
#square {
width: 40px;
height: 40px;
background-color: deepskyblue;
position: absolute;
left: 0;
top:0;
}
的Javascript
var rectangle = document.getElementById("rectangle");
var square = document.getElementById("square");
var currentPositionX = 0;
var currentPositionY = 0;
function moveSquare(event) {
if (event.keyCode == 37) {
currentPositionX -= 40;
square.style.left = currentPositionX + 'px';
if (currentPositionX <= 0) {
currentPositionX += 40;
}
}
if (event.keyCode == 38) {
currentPositionY -= 40;
square.style.top = currentPositionY + 'px';
if (currentPositionY <= 0) {
currentPositionY += 40;
}
}
if (event.keyCode == 39) {
currentPositionX += 40;
square.style.left = currentPositionX + 'px';
if (currentPositionX >= 280) {
currentPositionX -= 40;
}
}
if (event.keyCode == 40) {
currentPositionY += 40;
square.style.top = currentPositionY + 'px';
if (currentPositionY >= 160) {
currentPositionY -= 40;
}
}
}
document.onkeydown = moveSquare;
答案 0 :(得分:0)
我测试了代码,发现当你靠近边界时,它无法正常工作(也许这是原始问题?)。在这个我测试了另一个更简单的解决方案:我只是改变你的moveSquare函数,只有当你在你的范围内时才能工作(我的意思是,你不应该总是递增/递减位置,然后检查你是否超出界限纠正它。)
function moveSquare(event) {
if (event.keyCode == 37) {
if (currentPositionX > 0) {
currentPositionX -= 40;
square.style.left = currentPositionX + 'px';
}
}
if (event.keyCode == 38) {
if (currentPositionY > 0) {
currentPositionY -= 40;
square.style.top = currentPositionY + 'px';
}
}
if (event.keyCode == 39) {
if (currentPositionX < 280) {
currentPositionX += 40;
square.style.left = currentPositionX + 'px';
}
}
if (event.keyCode == 40) {
if (currentPositionY < 160) {
currentPositionY += 40;
square.style.top = currentPositionY + 'px';
}
}
}
这是jsfiddle:https://jsfiddle.net/epL4a9Lq/
请下次更具体地说明您的错误(我会在回答之前对此进行评论,但我还没有声誉)。
希望这有帮助!