【问题标题】:Loop a switch statement Javascript [closed]循环一个switch语句Javascript [关闭]
【发布时间】:2021-07-17 03:55:39
【问题描述】:

嘿,这是我的第一篇文章,我正在尝试重新创建谷歌恐龙游戏,但是当我打开页面时,会选择一个随机动画,但只有一次我需要一种方法来不断循环它,让我们说每秒一次。 “kubbur”是原版游戏中的仙人掌。

var kubbur = document.getElementById("kubbur");
var kubbur2 = document.getElementById("kubburTwo");
var kubbur3 = document.getElementById("kubburThree");
var randomKubbur = Math.floor(Math.random() * 3); //chooses a random number

switch(randomKubbur) {
    case 0:
            if(kubbur.classList !="animateKubbur1"){
            kubbur.classList.add ("animateKubbur1");
            }
            setTimeout(function(){
            kubbur.classList.remove("animateKubbur1");
            }, 1000)

        break;
    case 1:
            if(kubbur2.classList !="animateKubburTwo"){
            kubbur2.classList.add ("animateKubburTwo");
            }
            setTimeout(function(){
            kubbur2.classList.remove("animateKubburTwo");
            }, 1000)
        break;
    case 2:
            if(kubbur3.classList !="animateKubburThree"){
            kubbur3.classList.add ("animateKubburThree");
            }
            setTimeout(function(){
            kubbur3.classList.remove("animateKubburThree");
            }, 1000)
        break;

}

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花点时间阅读help centerHow to Ask
  • 您的问题是什么?如果您正在寻找代码审查,这里有一个堆栈交换站点。
  • @PaulRooney 抱歉,措辞不当。我需要在 700 毫秒到 1200 毫秒之间的随机时间循环并连续执行。但我不知道该怎么做。
  • 如果您需要代码审查,我为您准备了一份,但问题现在已结束。

标签: javascript loops switch-statement


【解决方案1】:

var kubburs = document.querySelectorAll(".kubbur");

// Create a function
function animate() {
  var classes      = ['animateKubbur1', 'animateKubburTwo', 'animateKubburThree'],
      randomKubbur = Math.floor(Math.random() * 3), // random number between 0-2
      elem         = kubburs[randomKubbur],
      className    = classes[randomKubbur];
      
  elem.classList.add(className);
  setTimeout(function() {
    elem.classList.remove(className);
  }, 1000);
  
  // Repeat it after 700-1200 ms
  setTimeout(animate, Math.random() * (1200 - 700) + 700);
}

// Call it
animate();
.kubbur { width: 50px; height: 50px; background: #ccc; display: inline-block; }
.animateKubbur1 { background: red; }
.animateKubburTwo { background: green; }
.animateKubburThree { background: blue; }
<div class="kubbur"></div>
<div class="kubbur"></div>
<div class="kubbur"></div>

【讨论】:

  • 非常感谢,效果很好!
猜你喜欢
  • 1970-01-01
  • 2014-11-25
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多