我试图制作一个javascript游戏,但我遇到了一个问题,我想确保如果一个if语句=true,它会执行一个函数,这现在是可行的,但它会一次又一次地执行它,我只需要它执行一次。
这就是我现在所拥有的:
//this is the js
setInterval(function () {
var characterTop = parseInt(
window.getComputedStyle(character).getPropertyValue("top")
)
var characterLeft = parseInt(
window.getComputedStyle(character).getPropertyValue("left")
)
if (characterTop > 200 && characterLeft > 700) {
document.getElementById("win").classList.toggle("active")
{stopMoveLeft();}
{stopMoveRight();}
{stopMoveDown();}
{stopMoveUp();}
}
}, 50);
/*this is the css*/
#win {
height: 100%;
width: 100%;
background-color: black;
position: fixed;
top: 600px;
transition: all 500ms linear;
}
#win.active {
top: 0px;
}
<!--this is the html-->
<div id="win"></div>
有人知道如何确保它保持检查,但只执行函数一次吗?
请尝试以下操作:
var intervalVar = setInterval(function () {
var characterTop = parseInt(
window.getComputedStyle(character).getPropertyValue("top")
)
var characterLeft = parseInt(
window.getComputedStyle(character).getPropertyValue("left")
)
if (characterTop > 200 && characterLeft > 700) {
document.getElementById("win").classList.toggle("active")
{stopMoveLeft();}
{stopMoveRight();}
{stopMoveDown();}
{stopMoveUp();}
clearInterval(intervalVar);
}
}, 50);
您可以添加一个布尔值来检查它是否已经运行了代码
var done = false;
//this is the js
setInterval(function () {
var characterTop = parseInt(
window.getComputedStyle(character).getPropertyValue("top")
)
var characterLeft = parseInt(
window.getComputedStyle(character).getPropertyValue("left")
)
if (characterTop > 200 && characterLeft > 700 && !done) {
done = true;
document.getElementById("win").classList.toggle("active")
{stopMoveLeft();}
{stopMoveRight();}
{stopMoveDown();}
{stopMoveUp();}
}
}, 50);
如果我没听错的话。。。
null
if (characterTop > 200 && characterLeft > 700) {
setInterval(function () {
var characterTop = parseInt(
window.getComputedStyle(character).getPropertyValue("top")
)
var characterLeft = parseInt(
window.getComputedStyle(character).getPropertyValue("left")
)
if (characterTop > 200 && characterLeft > 700) {
document.getElementById("win").classList.toggle("active")
{stopMoveLeft();}
{stopMoveRight();}
{stopMoveDown();}
{stopMoveUp();}
}, 50);
} else {}
#win {
height: 100%;
width: 100%;
background-color: black;
position: fixed;
top: 600px;
transition: all 500ms linear;
}
#win.active {
top: 0px;
}
<!--this is the html-->
<div id="win"></div>