开发者问题收集

JavaScript 仅允许在元素显示时点击

2017-09-23
52

我正在开发一款纯 JavaScript 游戏,我有一架可以发射导弹的飞机,因此我的想法是,当我点击它时,它会发射一枚导弹,几秒钟后导弹会回到它的位置并再次显示,它工作正常,但是当我多次点击时它会堆叠,所以发生的事情是导弹在多次点击中没有回到它的位置,我该如何解决这个问题?我怎样才能在 3 秒的时间内只允许一次点击?或者只允许在导弹准备好时点击!!! 这是我的代码!

 window.onclick = function()
{

    var $ball1 = document.getElementById("ball1");

    // shooting the missile using css transition to get some delay
    $ball1.style.top = "-12000px";

    // hide missile and get it back to it's position
    setTimeout(function(){
        $ball1.style = "display:none; top:71px";
    }, 500); 

    // show missile again on plane
    setTimeout(function(){
        $ball1.style = "display:block;";
    }, 1000);      

}
3个回答

一种简单的方法是使用变量来存储上次处理点击的时间,然后检查已经过去的时间。在我的示例中,我使用 lastTime 来存储时间,并在点击之间设置 3000ms (3 秒)的间隔。此示例的输出只是简单地记录到控制台,但您可以将其更改为您想要的任何内容。

var lastTime = -1;
window.onclick = function() {
  if (lastTime < 0 || (new Date().getTime() - lastTime >= 3000)) {
    lastTime = new Date().getTime();
    console.log("firing missile");
  } else {
    console.log("too soon");
  }

}
Angelos Chalaris
2017-09-23

要解决您面临的问题,您需要存储一个状态 allowNextClick ,您将根据该状态决定是否执行进一步的代码。

var allowNextClick = true;

window.onclick = function()
{

    if(!allowNextClick) {
        return;
    }
    allowNextClick = false;

    // allow every 3 seconds
    setTimeout(function() {
        allowNextClick = true;
    }, 3000);

    var $ball1 = document.getElementById("ball1");

    // shooting the missile using css transition to get some delay
    $ball1.style.top = "-12000px";

    // hide missile and get it back to it's position
    setTimeout(function(){
        $ball1.style = "display:none; top:71px";
    }, 500); 

    // show missile again on plane
    setTimeout(function(){
        $ball1.style = "display:block;";

        // allow next click after missile is back
        allowNextClick = true;
    }, 1000);      

}
Oleksandr Fedotov
2017-09-23
// define a Boolean to check if ball is just shoot
var canShot = true;

window.onclick = function() {

    if (canShoot) {
        var $ball1 = document.getElementById("ball1");

        // shooting the missile using css transition to get some delay
        $ball1.style.top = "-12000px";

        // turn the Boolean canShot to false to prevent multiple trigger
        canShot = false;

        // hide missile and get it back to it's position
        setTimeout(function(){

            $ball1.style = "display:none; top:71px";
        }, 500); 

        // show missile again on plane
        setTimeout(function(){

            $ball1.style = "display:block;";
            // turn the Boolean canShot to true to make the ball can be shoot
            canShot = true;
       }, 1000);
    }
}
Rex Hsu
2017-09-23