这个故事是一个坠落的气球。如果你成功点击气球("停止"功能(,你就赢了。否则,如果它下降450像素,你就输了。
问题是当我按下气球时:它会更改src、提醒我和clearInterval——现在我认为它会停止或等待下一个事件。但是,在我点击警报"确定"后,它一直在下降。。。
我的代码:
function Start() {
num = Math.floor(Math.random() * 501);
document.getElementById("balon").style.left = num + 'px';
var id = setInterval(function() {
if (posX > 450 && ok) {
alert("Looser");
clearInterval(id);
} else {
posX += Vpos * dt;
document.getElementById("balon").style.top = posX + 'px';
}
}, dt);
}
function Stop() {
document.getElementById("balon").src = 'JS Pics/balon2.gif';
alert("Winner");
clearInterval(id);
}
最后,我找到了一些方法,通过添加布尔变量来阻止它。请参见以下内容:无论如何,我不确定为什么会发生这种情况(很乐意解释(或其他解决方法Thanx。
function Start() {
num = Math.floor(Math.random() * 501);
document.getElementById("balon").style.left = num + 'px';
var id = setInterval(function() {
if (posX > 450 && ok) {
alert("Looser");
clearInterval(id);
} else {
if (ok) {
posX += Vpos * dt;
document.getElementById("balon").style.top = posX + 'px';
} else {
clearInterval(id);
}
}
}, dt);
}
function Stop() {
ok = false;
document.getElementById("balon").src = 'JS Pics/balon2.gif';
alert("Winner");
clearInterval(id);
}
id
在Start
函数的范围内,因此在Stop
函数的范围中未定义
您可以在两个函数之外声明它,这样他们就可以访问它:
var id;
function Start() {
num = Math.floor(Math.random() * 501);
document.getElementById("balon").style.left = num + 'px';
id = setInterval(function () {
if (posX > 450 && ok) {
alert("Looser");
clearInterval(id);
}
else {
posX += Vpos * dt;
document.getElementById("balon").style.top = posX + 'px';
}
}, dt);
}
function Stop() {
document.getElementById("balon").src = 'JS Pics/balon2.gif';
alert("Winner");
clearInterval(id);
}
您对ok
的修复是有效的,因为您没有用关键字var
声明它,所以它被分配给window
对象(或者您在外部范围中声明了它,但忘记在代码片段中追加(。