当我试图仅在第一个“运动命令”中将div(坦克)向右移动时,并且仅在那个方向上,我遇到问题,我的div向右射出几千个像素,方式离开屏幕区域。希望有人能帮我看看为什么会这样。
function animate() {
var tank = document.getElementById("tank");
tank.style.marginLeft="360px";
tank.style.marginTop="440px";
window.xpos = tank.style.marginLeft;
window.ypos = tank.style.marginTop;
window.x = xpos.replace("px","");
window.y = ypos.replace("px","");
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
if (x > 0) {
x = x - 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '39') {
if (x < 70) {
x = x + 20;
tank.style.marginLeft = x + "px";
}
} else if (e.keyCode == '38') {
if (y > 0) {
y = y - 20;
tank.style.marginTop = y + "px";
}
} else if (e.keyCode == '40') {
if (y < 440) {
y = y + 20;
tank.style.marginTop = y + "px";
}
}
}
checkKey(e);
}
window.lives = 3;
function destroy() {
if (lives != 0) {
alert("Life Lost!");
lives--;
window.collision == false;
animate();
} else {
alert("Try Again!");
}
}
window.collision = true;
function state() {
if (collision == false) {
window.state = 1;
} else if (collision == true) {
window.state = 0;
}
return state;
}
state();
if (state == 1) {
animate();
} else {
destroy();
}
答案 0 :(得分:0)
您认为自己正在进行数学运算,但实际上您正在进行字符串连接。在Javascript“360”-20等于340,因为在这种情况下,字符串被转换为数字,然后使用两个数值执行算术减法,但是对于加号运算符应用不同的规则集:在这种情况下为“360” +20产生“36020”,因为该数字被转换为字符串,然后连接两个字符串。
这样做:
window.x = Number(xpos.replace("px",""));
window.y = Number(ypos.replace("px",""));