【问题标题】:have an array with colors that I want to rotate infinitely through setInterval有一个颜色数组,我想通过 setInterval 无限旋转
【发布时间】:2021-05-04 22:22:47
【问题描述】:

所以我有一个包含少量颜色的简单数组和一个将这些颜色添加到 body 的 backgroundColor 属性的函数。我正在使用 setInterval 来遍历颜色,但是当它遍历数组时它会停止。我希望它继续前进,要么从头开始,要么也可以以相反的顺序进行。我该怎么做?

let colors = ['crimson','dodgerblue','gold', 'deeppink'];
const body = document.body;
let index = 0;

function change() {
body.style.backgroundColor = colors[index++];
}

var timer = setInterval(change, 4000);

【问题讨论】:

    标签: javascript setinterval infinite


    【解决方案1】:

    您只需要一点额外的逻辑来检查index,如果它超出了数组的末尾,则将其重置为0。

    最简单的方法是使用%“模数”运算符:

    function change() {
      index = (index + 1) % colors.length;
      body.style.backgroundColor = colors[index];
    }
    

    【讨论】:

    • 啊,谢谢!是的,我认为它与模数有关。从来没有完全掌握它以及它是如何工作的。
    【解决方案2】:

    您必须确保索引到达数组的末尾,如果是,请重置它。 比如:

    function change() {
      index = index === colors.length - 1 ? 0 : index++;
      body.style.backgroundColor = colors[index];
    }
    

    【讨论】:

      【解决方案3】:

      let colors = ['green','dodgerblue','gold', 'deeppink'];
      const body = document.body;
      let index = 0;
      
      function change() {
      console.log('going')
      body.style.backgroundColor = colors[index++];
      if(index == colors.length) {
          index = 0;
        }
      }
      
      var timer = setInterval(change, 1000);

      我只是添加了一些逻辑,如果索引到达数组末尾,则将其重置为零

      【讨论】:

        猜你喜欢
        • 2023-04-10
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-07-18
        • 1970-01-01
        • 2015-06-02
        • 2013-12-31
        • 1970-01-01
        相关资源
        最近更新 更多