Change background color with a loop onclick

喜欢而已 提交于 2021-02-16 20:58:06

问题


here is my js fiddle : http://jsfiddle.net/pYM38/16/

 var box = document.getElementById('box');

 var colors = ['purple', 'yellow', 'orange', 'brown', 'black'];

 box.onclick = function () {

    for (i = 0; i < colors.length; i++) {

        box.style.backgroundColor = colors[i];


      }

};

I'm in the process of learning JavaScript. I was trying to get this to loop through each color in the array, but when i click the box (demonstration on jsfiddle) it goes to the last element in the array.


回答1:


Here are two methods, depending on what you're up to:

Loop to Next on Click

var box = document.getElementById('box'),
    colors = ['purple', 'yellow', 'orange', 'brown', 'black'];

box.onclick = function () {
    color = colors.shift();
    colors.push(color);

    box.style.backgroundColor = color;
};

http://jsfiddle.net/pYM38/17/

Loop Through All on Click

var box = document.getElementById('box'),
    colors = ['purple', 'yellow', 'orange', 'brown', 'black'];

box.onclick = function () {
    (function loop(){
        var color = colors.shift();

        box.style.backgroundColor = color;

        if (colors.length) {
            setTimeout(loop, 1000);
        }
    })();
};

http://jsfiddle.net/pYM38/23/

Restarts on Next Click

var box = document.getElementById('box'),
    colors = ['purple', 'yellow', 'orange', 'brown', 'black'];

box.onclick = function () {
    var set = colors.slice(0);

    (function loop(){
        var color = set.shift();

        box.style.backgroundColor = color;

        if (set.length) {
            setTimeout(loop, 1000);
        }
    })();
};



回答2:


you want it to be animated, or delayed?

Because your example works perfectly, you are looping through all colors and it is so fast that you see only the last one.

var box = document.getElementById('box');

 var colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
 var running = 0;    
 box.onclick = function () {
    if(running>0) return;
    for (i = 0; i < colors.length; i++) {
        running++;
        setTimeout(function() {
             box.style.backgroundColor = colors[i];
             running--;
        }, 1000);

      }

};


来源:https://stackoverflow.com/questions/23818675/change-background-color-with-a-loop-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!