我想重复代码,但不知道如何使用循环

I want to repeat code but don't know how t use loops

本文关键字:不知道 何使用 循环 代码      更新时间:2023-09-26

我有这个代码:

.js:

function change_color(color) {
$("body").animate({ backgroundColor:color }, '1000');
}
setTimeout(function () {
    change_color('#4AC900'
    );
}, 500);
setTimeout(function () {
    change_color('#964514'
    );
}, 1500);
setTimeout(function () {
    change_color('#EE0000'
    );
}, 1500);
setTimeout(function () {
    change_color('#FFE303'
    );
}, 1500);
setTimeout(function () {
    change_color('#8E388E'
    );
}, 1500);
setTimeout(function () {
    change_color('#FF00AA'
    );
}, 1500);

我想反复使用它,但把它放在一个 while 循环中只会使网站崩溃,有人可以帮忙吗?

这是网站...这是我的弟弟网站不是我的...http://timothy.techbytbone.com/isaac.php

var colors = ['#4AC900', '#964514', '#EE0000', '#FFE303', '#8E388E', '#FF00AA'],
    len = colors.length,
    i;
for (i = 0; i < len; i++) {
    (function(i, color) {
        setTimeout(function () {
            change_color(color);
        }, (i + 1) * 500);
    })(i, colors[i]);
}
这就是

你所需要的:

js小提琴演示

var c = 0;
var colors = ['#4AC900','#964514','#EE0000','#FFE303','#8E388E','#FF00AA'];
(function loop(){         
    $('body').stop().animate({backgroundColor : colors[c++%colors.length] }, 1000, loop);  
})();

(请注意,您需要使用 jQuery UI 对 CSS background-color 属性进行动画处理(

var colors = {'#4AC900': 500,
              '#964514': 1500,
              // etc. Just continue with the color-millisecond combinations
             }
for(key in colors) {
 setTimeout(function () {
    change_color(key);
 }, colors[key]);
}

您的循环崩溃,因为您无法在浏览器加载时设置所有必要的超时。这是应该可以工作的代码版本。

var colors = ['#4AC900', '#964514', '#EE0000', '#FFE303', '#8E388E', '#FF00AA'];
var currentColorIndex = 0;
var scheduleChange;
scheduleChange = function() {
    change_color(currentColorIndex);
    currentColorIndex = (currentColorIndex + 1) % colors.length
    setTimeout(scheduleChange, 1000);
};
setTimeout(scheduleChange, 500);
function change_color(color) {
  $("body").animate({ backgroundColor:color }, '1000');
}
setTimeout(function() {
  change_color('#4AC900')
}, 500);
colors = ['#964514', '#EE0000', '#FFE303', '#8E388E', '#FF00AA']
interval = setInterval(function() {
  if (! a.length) {
    return clearInterval(interval);
  }
  change_colors(a.shift());
}, 1500);

玩得愉快。你应该了解闭包,以免弄乱setIntervals。有大量的库可以动画颜色和其他东西。我可以推荐墨菲斯。